<?php

/**
* @current article.php
* @author   LiuYang <liu_yang@haibao.com>
* @date 2017年2月14日 下午2:33:53
*/
namespace haibao\jiepai\data;

use \haibao\jiepai\data\CmsArticleTags as CmsArticleTagsData;
use \haibao\jiepai\data\CmsArticleContent as CmsArticleContentData;
use \haibao\jiepai\data\CmsArticleStatistic as CmsArticleStatisticData;
use \haibao\jiepai\model\filter\article\CmsArticles as CmsArticlesFilter;
use \haibao\jiepai\data\CmsArticleCelebrity as CmsArticleCelebrityData;

use \haibao\jiepai\cache\App as AppRedis;
use haibao\classlibrary\jiepai\Config;

class Article extends \haibao\jiepai\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\jiepai\model\data\article\CmsArticles');
    }
    
    public function getArticleById($articleIds){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
        $sql = "SELECT ArticleID,Title FROM cms_articles WHERE ArticleID IN (".$str.")";
        $result = $this->query($sql, $articleIds);
        $returnArticle = array();
        while ($row = $result->fetch_assoc()){
            $returnArticle[$row['ArticleID']] = $row;
        }
        return $returnArticle;
    }
    
    public function getArticlePicById($articleIds){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
        $sql = "SELECT ID,ArticleID,ContentInfo,Type FROM cms_article_content WHERE ArticleID IN (".$str.") AND Type=6";
        $result = $this->query($sql, $articleIds);
        $returnArticle = array();
        while ($row = $result->fetch_assoc()){
            $returnArticle[$row['ArticleID']] = $row;
        }
        return $returnArticle;
    }
    public function addArticleData($model){
        $this->beginTranscation();
        try{
            $this->add($model);
            $this->addArticleTags($model);
            $this->addArticleStatistic($model);
            $this->addArticleContent($model);
            if($model->CmsArticlesRec){
                $this->InsertOtherArticles($model->Id,$model->CmsArticlesRec,1);
            }
            $this->insertArticlesCelebrity($model);
            /* if($model->CmspersonTag){
                $this->InsertArticleArea($model->Id,$model->CmspersonTag,$model->Type);
            } */
        } catch(\Exception $e){
            throw $e;
        }
        $this->endtranscation();
        return $model;
    }
    public function addArticleTags($model){
        if($model->TagInfoList){
            foreach ($model->TagInfoList as $value){
                $value->ArticleID = $model->Id;
            }
            $cmsArticleTagsData = new CmsArticleTagsData();
            $cmsArticleTagsData->addAll($model->TagInfoList);
        }
    }
    public function addArticleStatistic($model){
        if($model->ArticleStatistic){
            $model->ArticleStatistic->ArticleID = $model->Id;
            $cmsArticleStatisticData = new CmsArticleStatisticData();
            $cmsArticleStatisticData->add($model->ArticleStatistic);
        }
    }
    
    public function addArticleContent($model){
        if($model->ArticleContentInfo){
            foreach ($model->ArticleContentInfo as $value){
                $value->ArticleID = $model->Id;
            }
            $cmsArticleContentData = new CmsArticleContentData();
            $cmsArticleContentData->addAll($model->ArticleContentInfo);
        }
    }
    
    public function insertArticlesCelebrity($model){
        if($model->celebrityList){
            foreach ($model->celebrityList as $key=>$val){
                $val->ArticleID = $model->Id;
            }    
            $cmsArticleCelebrityData = new CmsArticleCelebrityData();
            $cmsArticleCelebrityData->addAll($model->celebrityList);
        }
    }
    public function updateArticleData($model){
        $articleModel = $this->packArticleFilter($model);
        $this->beginTranscation();
        try{
            $this->updateById($model->Id,$articleModel);
            $this->updateArticleTags($model);
            $this->updateArticleContent($model);
            if($model->CmsArticlesRec){
                $this->UpdateOtherArticles($model->Id,$model->CmsArticlesRec,1);
            }
            $this->updateArticlesCelebrity($model);
            /* if($model->CmspersonTag){
                $this->InsertArticleArea($model->Id,$model->CmspersonTag,$model->Type);
            } */
        } catch(\Exception $e){
            throw $e;
        }
        $this->endtranscation();
    }
    public function updateArticlesCelebrity($model){
        $sql = "DELETE FROM cms_article_celebrity WHERE ArticleID=%s";
        $this->query($sql,array($model->Id));
        if($model->celebrityList){
            $cmsArticleCelebrityData = new CmsArticleCelebrityData();
            $cmsArticleCelebrityData->addAll($model->celebrityList);
        }
    }
    public function packArticleFilter($model){
        $cmsArticlesFilter = new CmsArticlesFilter();
        $cmsArticlesFilter = array(
            CmsArticlesFilter::CONDITION_FIELD_NAME_COLUMN_ID =>$model->ColumnID,
            CmsArticlesFilter::CONDITION_FIELD_NAME_EDITOR_ID =>$model->EditorID,
            CmsArticlesFilter::CONDITION_FIELD_NAME_TYPE =>$model->Type,
            CmsArticlesFilter::CONDITION_FIELD_NAME_TITLE =>$model->Title,
            CmsArticlesFilter::CONDITION_FIELD_NAME_SUBTITLE_TYPE =>$model->SubtitleType,
            CmsArticlesFilter::CONDITION_FIELD_NAME_SUBTITLE =>$model->Subtitle,
            CmsArticlesFilter::CONDITION_FIELD_NAME_SUMMARY =>$model->Summary,
            //CmsArticlesFilter::CONDITION_FIELD_NAME_CREATE_TIME =>$model->CreateTime,
            CmsArticlesFilter::CONDITION_FIELD_NAME_UPDATE_TIME =>$model->UpdateTime,
            CmsArticlesFilter::CONDITION_FIELD_NAME_PUBLISH_TIME =>$model->PublishTime,
            CmsArticlesFilter::CONDITION_FIELD_NAME_PUBLISH_USER_ID =>$model->PublishUserID,
            CmsArticlesFilter::CONDITION_FIELD_NAME_PUBLISH_STATUS =>$model->PublishStatus,
            CmsArticlesFilter::CONDITION_FIELD_NAME_SOURCE =>$model->Scores,
            CmsArticlesFilter::CONDITION_FIELD_NAME_FLAG =>$model->Flag,
            CmsArticlesFilter::CONDITION_FIELD_NAME_CONTENT_LINK =>$model->ContentLink,
            CmsArticlesFilter::CONDITION_FIELD_NAME_PICTURE_NUM =>$model->PictureNum,
            CmsArticlesFilter::CONDITION_FIELD_NAME_IS_HEAD_LINE =>$model->IsHeadLine,
            CmsArticlesFilter::CONDITION_FIELD_NAME_HAIBAO_ID =>$model->HaibaoID,
            CmsArticlesFilter::CONDITION_FIELD_NAME_SOURCE =>$model->Source,
            CmsArticlesFilter::CONDITION_FIELD_NAME_SOURCE_TAGS =>$model->SourceTags,
            CmsArticlesFilter::CONDITION_FIELD_NAME_HTML =>$model->Html,
            CmsArticlesFilter::CONDITION_FIELD_NAME_TAG_LIST =>$model->TagList,
            CmsArticlesFilter::CONDITION_FIELD_NAME_BROWSE_NUM =>$model->BrowseNum,
            CmsArticlesFilter::CONDITION_FIELD_NAME_OLD_JIEPAI_STATISTIC =>$model->OldJiepaiStatistic,
            CmsArticlesFilter::CONDITION_FIELD_NAME_3DPICTURE =>$model->_3DPicture,
            CmsArticlesFilter::CONDITION_FIELD_NAME_ENDTIME =>$model->EndTime,
        );
        return $cmsArticlesFilter;
    }
    
    private function updateArticleTags($model){
        $sql = "delete from cms_article_tags where ArticleID=".$model->Id;
        $result = $this->query($sql);
        if($model->TagInfoList){
            $cmsArticleTagsData = new CmsArticleTagsData();
            $cmsArticleTagsData->addAll($model->TagInfoList);
        }
    }
    
    private function updateArticleContent($model){
        $sql = "delete from cms_article_content where ArticleID=".$model->Id;
        $this->query($sql);
        if($model->ArticleContentInfo){
            $cmsArticleContentData = new CmsArticleContentData();
            $cmsArticleContentData->addAll($model->ArticleContentInfo);
        }
    }
    
    public function getArticleStatisticList($conditions){
        $sql = "SELECT
                    count(cas.ArticleID) AS ArticleNum,
                    (SUM(cas.AppBrowseNum) + SUM(cas.WebBrowseNum)) AS BrowseNum, 
                    (SUM(cas.CommentNum) + SUM(cas.ReplyNum)) AS CommentNum,
                    (SUM(cas.CollectArticleNum) + SUM(cas.CollectPictureNum)) AS CollectNum,
                    SUM(cas.PraiseNum) AS PraiseNum,
                    SUM(cas.ShareNum) AS ShareNum,
                    SUM(cas.GoodsNum) AS GoodsNum,
                    SUM(cas.HotScores) AS HotScores
                FROM
	               `cms_article_statistic` cas
                LEFT JOIN cms_articles ca ON cas.ArticleID = ca.ArticleID
                WHERE ca.Flag = 0
                AND ca.PublishStatus = 1";
        if(isset($conditions['start']) && $conditions['start']){
            $sql .= " AND ca.PublishTime >= '".$conditions['start']."'";
        }
        if(isset($conditions['end']) && $conditions['end']){
            $sql .= " AND ca.PublishTime < '".$conditions['end']."'";
        }
        
        if(isset($conditions['ColumnId']) && $conditions['ColumnId']){
           $type = in_array($conditions['ColumnId'], array(1,7,4,21,24)); //标准混排
           if($type){
               $sql .= " AND ca.ColumnID = ".$conditions['ColumnId'];
           }else{
               $sql .= " AND ca.Type = ".$conditions['ColumnId'];
           }
	    }
	    if(isset($conditions['UserId']) && $conditions['UserId']){
	        $guiseInfo = \haibao\cms\business\Guise::getGuiseListByUserId($conditions['UserId']);
	        $guiseIds = array();
	        foreach ($guiseInfo as $val){
	            array_push($guiseIds, $val['GuiseId']);
	        }
	        if($guiseIds){
	            $sql .= " AND ca.EditorID IN (".implode(',', $guiseIds).")";
	        }
	    }
	    $result = $this->query($sql);
	    
	    $data = array();
	    while ($row = $result->fetch_assoc()){
	        $data = $row;
	    }
	    return $data;
    }
    public function getArticleClickNumsByArticleId($articleIds){
        if(!$articleIds){
            return false;
        }
        $articleIds = (array)$articleIds;
        $articleIdStr = implode(',', $articleIds);
        $sql='SELECT a.ArticleID,a.Scores,c.ContentInfo,COUNT(com.CommentID) AS CommentCount,COUNT(rep.CommentID) AS CommentReplyCount,sta.AppBrowseNum,sta.CommentPraiseNum,sta.PraiseNum
            FROM cms_articles a
            LEFT JOIN cms_article_content c ON a.ArticleID = c.ArticleID
            AND c.Type = 0
            LEFT JOIN cms_comment com ON com.TypeID = a.ArticleID
            AND com.Type = 0
            LEFT JOIN cms_comment_reply rep ON rep.CommentID = com.CommentID
            LEFT JOIN cms_article_statistic sta ON a.ArticleID = sta.ArticleID
            WHERE a.ArticleID IN ('.$articleIdStr.')
            GROUP BY a.ArticleID';
        $result = $this->query($sql);
        $data = array();
        while ($result->fetch_assoc()){
            if(!isset($data[$result->getData('ArticleID')])){
                $nums = array(
                    'ArticleID'=>$result->getData('ArticleID'),
                    'ContentInfo'=>$result->getData('ContentInfo'),
                    'Picture'=>$result->getData('Picture'),
                    'Scores'=>$result->getData('Scores'),
                    'CommentCount'=>$result->getData('CommentCount')+$result->getData('CommentReplyCount'),
                    'AppBrowseNum'=>$result->getData('AppBrowseNum'),
                    'PraiseNum'=>$result->getData('PraiseNum'),
                    'CommentPraiseNum'=>$result->getData('CommentPraiseNum'),
                );
                $data[$result->getData('ArticleID')] = $nums;
            }
        }
        return $data;
    }
    
    function getArticleStatisticDetailList($articleId,$page,$dataItem){
        $sql = "SELECT
            	cas.*, ca.Scores,
            	cc.ColumnName,
                cac.ContentInfo
            FROM
            	cms_article_statistic cas
            LEFT JOIN cms_articles ca ON cas.ArticleID = ca.ArticleID
            INNER JOIN cms_article_content cac ON cac.ArticleID = ca.ArticleID
            AND cac.Type = 0
            LEFT JOIN cms_columns cc ON cc.ColumnID = ca.ColumnID
            WHERE
            	ca.Flag = 0
            AND ca.PublishStatus = 1
            AND cac.Flag = 0";
           $countSql = "SELECT
                    	count(*) AS count
                    FROM
                    	cms_article_statistic cas
                    LEFT JOIN cms_articles ca ON ca.ArticleID = cas.ArticleID
                    WHERE
                    	ca.Flag = 0
                    AND ca.PublishStatus = 1";
            if(isset($dataItem['startDate']) && $dataItem['startDate']){
                $sql .= " AND ca.PublishTime >= '".$dataItem['startDate']."'";
                $countSql .= " AND ca.PublishTime >= '".$dataItem['startDate']."'";
            }
            if(isset($dataItem['endDate']) && $dataItem['endDate']){
                $sql .= " AND ca.PublishTime <= '".$dataItem['endDate']."'";
                $countSql .= " AND ca.PublishTime <= '".$dataItem['endDate']."'";
            }
            if($articleId){
                $sql .= " AND ca.ArticleID = ".$articleId;
                $countSql .= " AND ca.ArticleID = ".$articleId;
            }
            $sql .= 'ORDER BY ca.PublishTime desc';
            $limit = " Limit 0,20";
            if($page > 1){
                $startCount = ($page - 1) * 20 + 1;
                $limit = " Limit ".$startCount.",20";
            }
            $sql .= $limit;
            $result = $this->query($sql);
            $data = array();
            while ($row = $result->fetch_assoc()){
                $data[$row['ArticleID']] = $row;
            }
            $countresult = $this->query($countSql);
            $dataCount = array();
            while ($countrow = $countresult->fetch_assoc()){
                $dataCount = $countrow;
            }
            return  array($data,$dataCount);
    }
    
    function CheckJuryDate($publishTime, $endTime, $articleId){
        $sql = 'SELECT * FROM cms_articles WHERE Type=108 AND Flag=0 AND PublishStatus=1 ';
        
        if($articleId){
            $sql .= ' AND ArticleID!='.$articleId;
        }
        $sql .= ' AND EndTime>"'.$publishTime.'" AND PublishTime<"'.$endTime.'" ORDER BY EndTime DESC LIMIT 1';
        $result = $this->query($sql);
        
        $dataTime = array();
        while ($row = $result->fetch_assoc()){
            $dataTime = $row;
        }
        $timeIn = '';
        if(count($dataTime)>0){
            $timeIn = $dataTime['EndTime']->format('Y-m-d H:i:s');
        }
        return  $timeIn;
    }
    
    /**
     *给评审团打分 
     * @param unknown $articleId
     * @param unknown $item   Array('ContentIndex' => 1 'IsLike' => 0)
     * @param unknown $userId
     * @param unknown $visitorId
     */
    function PointJuryArticle($articleId,$item, $userId, $visitorId){
        if($userId>0){
            $type = 1;
            $typeId = $userId;
        }else{
            $type = 2;
            $typeId = $visitorId;
        }
        $deleteSql = "UPDATE cms_jury_action SET Flag=-1 WHERE Type=%s AND TypeID=%s AND ArticleID=%s AND ContentIndex=%s";
        $this->query($deleteSql,array($type,$typeId,$articleId,$item['ContentIndex']));
        $sql = "INSERT INTO cms_jury_action SET ArticleID=%s,FashionistaID='',ContentIndex=%s,IsLike=%s,Type=%s,CreateTime=%s,TypeID=%s,Flag=0";
        $this->query($sql,array($articleId,$item['ContentIndex'],$item['IsLike'],$type,new \DateTime(),$typeId));
    }
    /**
     * 删除评审团默认的喜欢和不喜欢
     * @param unknown $articleId  文章ID
     * @param unknown $userIds  添加时的用户ID array(1,2)
     */
    function delJuryActionList($articleId,$userIds){
        $sql = 'DELETE FROM cms_jury_action WHERE ArticleID='.$articleId.' AND Type IN ('.implode(',', $userIds).')';
        $this->query($sql);
    }
    function UpdateOtherArticles($articleId,$tagIdArr,$type){
        $sql = 'DELETE FROM cms_articles_rec WHERE TypeID=%s AND Type=%s';
        $this->query($sql,array($articleId,$type));
        $this->InsertOtherArticles($articleId, $tagIdArr, $type);
    }
    function InsertOtherArticles($articleId,$tagIdArr,$type){
        $tagIdArrList = array();
        $key = 0;
        foreach ($tagIdArr as $list){
            foreach ($list['tagId'] as $k=>$v){
               $temp = explode('###', $v);
               $tagIdArrList[$key]['Id'] = $temp[0];
               $tagIdArrList[$key]['count'] = $list['count'];
               $tagIdArrList[$key]['type'] = $list['type'];
               $key++;
            }
        }
        $dataInfo = array();
        foreach ($tagIdArrList as $k=>$v){
            $info = $this->CmsGetArticlesByTag($v['Id'], $v['count'], $articleId,$v['type']);
            if($info){
                foreach ($info as $m=>$n){
                    array_push($dataInfo, array($articleId,$type,$n['ArticleID'],new \DateTime(),0));
                }
            }
        }
        if($dataInfo){
            foreach ($dataInfo as $k=>$v){
                $sql = 'INSERT INTO cms_articles_rec (TypeID,Type,ArticleID,CreateTime,Flag) values (%s,%s,%s,%s,%s)';
                $this->query($sql,$v);
            }
        }
    }
    
    function CmsGetArticlesByTag($tagId, $count, $articleId,$tagType) {
        $date = date("Y-m-d",strtotime("-60 days"));
        if($tagType == 1){
            $sql = "SELECT a.ArticleID
                FROM cms_article_celebrity t
                LEFT JOIN cms_articles a ON t.ArticleID=a.ArticleID
                WHERE t.CelebrityID=".$tagId." AND a.Flag=0 AND a.PublishStatus=1 and a.Type in (1,2) and a.PublishTime>'".$date."'";
        }else{
            $sql = "SELECT a.ArticleID
                FROM cms_article_tags t
                LEFT JOIN cms_articles a ON t.ArticleID=a.ArticleID
                WHERE t.TagID=".$tagId." AND a.Flag=0 AND a.PublishStatus=1 and a.Type in (1,2) and a.PublishTime>'".$date."'";
        }
       
        if ($articleId) {
            $sql .= " AND a.ArticleID != ".$articleId;
        }
        $sql .= " ORDER BY a.CreateTime DESC LIMIT ".$count;
        $result = $this->query($sql);
        
        $data = array();
        while ($row = $result->fetch_assoc()){
            array_push($data, $row);
        }
        return  $data;
    }
    /* 增加人物类别 */
    function InsertArticleArea($articleId,$personTag,$articleType){
        $ids = array();
        if($articleType == 2 && count($personTag)>0){
            foreach ($personTag as $list){
                foreach ($list as $k=>$v){
                   $temp = explode('###', $v);
                   array_push($ids, $temp[0]);
                }
            }
            $str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
            $sql = "SELECT cf.DevelopArea,cf.DevelopArea2,cf.Title
                    FROM cms_fashionistas cf
                    WHERE cf.FashionistaID IN (".$str.")";
            $result = $this->query($sql,$ids);
            $data = array();
            while ($row = $result->fetch_assoc()){
                if($row['DevelopArea']){
                    array_push($data, array($articleId,$row['DevelopArea'],0,new \DateTime(),0));
                }
                if($row['DevelopArea2']){
                    array_push($data, array($articleId,$row['DevelopArea2'],0,new \DateTime(),0));
                }
                if($row['Title']){
                    array_push($data, array($articleId,$row['Title'],0,new \DateTime(),0));
                    if ($row['Title'] == \haibao\jiepai\model\data\tag\CmsTags::TAG_ID_STAR) {
                        array_push($data, array($articleId,\haibao\jiepai\model\data\tag\CmsTags::TAG_ID_COLUMN_STAR,0,new \DateTime(),0));
                    } else if ($row['Title'] == \haibao\jiepai\model\data\tag\CmsTags::TAG_ID_BLOGGER) {
                        array_push($data, array($articleId,\haibao\jiepai\model\data\tag\CmsTags::TAG_ID_COLUMN_BLOGGER,0,new \DateTime(),0));
                    } else if ($row['Title'] == \haibao\jiepai\model\data\tag\CmsTags::TAG_ID_FASHION) {
                        array_push($data, array($articleId,\haibao\jiepai\model\data\tag\CmsTags::TAG_ID_COLUMN_FASHION,0,new \DateTime(),0));
                    }
                }
                if(in_array(\haibao\jiepai\model\data\tag\CmsTags::TAG_ID_NONAME,$ids)){
                    array_push($data, array($articleId,\haibao\jiepai\model\data\tag\CmsTags::TAG_ID_FASHION,0,new \DateTime(),0));
                }
            }
            $this->InsertArticleTags($data,$articleId);
       }
    }
    
    function InsertArticleTags($data,$articleId) {
        foreach ($data as $k=>$v){
            $sql = 'INSERT INTO cms_article_tags (ArticleID,TagID,EditorID,CreateTime,Flag) values (%s,%s,%s,%s,%s)';
            $this->query($sql,$v);
        }
        $tagSql = 'SELECT t.TagName,t1.TagName as SecondName 
                FROM cms_article_tags a 
                LEFT JOIN cms_tags t ON a.TagID=t.TagID
                LEFT JOIN cms_fashionistas f ON t.TagID=f.FashionistaID 
                LEFT JOIN cms_tags t1 ON f.SecondName=t1.TagID 
                WHERE ArticleID=%s';
        $data = $this->query($tagSql,array($articleId));
        $dataList = array();
        while ($row = $data->fetch_assoc()){
            array_push($dataList, $row['TagName']);
        }
        $tagStr = implode('###',$dataList).'###';
        $laSql = 'update cms_articles set TagList=%s where ArticleID=%s';
        $this->query($laSql,array($tagStr,$articleId));
   }
  function CheckStatus($articleId){
      $sql = "SELECT Flag,PublishStatus,Type FROM cms_articles WHERE ArticleID=%s";
      $result = $this->query($sql,array($articleId));
      
      $data = array();
      while ($row = $result->fetch_assoc()){
          array_push($data, $row);
      }
      return  $data;
  }
   //article 里直接查询
   function getArticles($type,$cursor) {
       $selectSql = 'SELECT ';
       $otherSql = 'FROM cms_articles a 
                 LEFT JOIN cms_article_content c ON a.ArticleID=c.ArticleID AND c.Type=0
                 LEFT JOIN cms_article_content c2 on a.ArticleID=c2.ArticleID AND c2.Type=6';
       
        switch ($type) {
            case 1: //首页文章
                $selectSql .= 'DISTINCT a.ArticleID,a.PublishTime,a.Title,a.Type,a.PictureNum,a.ContentLink,c.ContentInfo as ContentInfo1,c2.ContentInfo as ContentInfo2 ';

                $otherSql .= ' LEFT JOIN cms_columns m on a.ColumnID=m.ColumnID 
                               WHERE (m.Flag =0 OR m.Flag=null) and a.Flag=0  AND a.PublishStatus = 1 AND ';
                $otherSql .= '(c.Type=0 OR c.Type=6) AND ';
                $otherSql .= ' a.Type in (1,2,101,102,103,104,105,106,108) ';
                $otherSql .= " AND a.PublishTime <= '".date('Y-m-d H:i:s')."'";
                if ($cursor) {
                    $otherSql .= 'AND a.PublishTime < "' .date('Y-m-d H:i:s',intval($cursor)). '"';
                }
                $otherSql .= " order by a.PublishTime DESC limit ".\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE);
                break;
            case 2: //首页头条
                $selectSql .= ' a.ArticleID,a.Title,a.Summary,a.Type,a.IsHeadLine,m.ColumnName ';
                $otherSql .= 'LEFT JOIN cms_columns m ON a.ColumnID=m.ColumnID 
                              WHERE a.IsHeadLine=1 and a.Flag=0 AND a.PublishStatus = 1 order by a.PublishTime desc limit '.\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::HEAD_LINE_LIMIT);
                break;
        }
        $selectSql.=$otherSql;
        $result = $this->query($selectSql);

        $dataList = array();
        while ($row = $result->fetch_assoc()){
            array_push($dataList, $row);
        }
        if($dataList){
            $dataList = $this->mergeDataAndImage($dataList,'ContentInfo2');
            foreach ($dataList as $key=>$val){
                $dataList[$key]['Picture2'] = $val['Picture'];
                $dataList[$key]['CropX2'] = $val['CropX'];
                $dataList[$key]['CropY2'] = $val['CropY'];
                $dataList[$key]['CropWidth2'] = $val['CropWidth'];
                $dataList[$key]['CropHeight2'] = $val['CropHeight'];
                $dataList[$key]['FileWidth2'] = $val['FileWidth'];
                $dataList[$key]['FileHeight2'] = $val['FileHeight'];
                $dataList[$key]['Ratio2'] = $val['Ratio'];
                unset($dataList[$key]['Picture'],$dataList[$key]['CropX'],$dataList[$key]['CropY'],$dataList[$key]['CropWidth'],$dataList[$key]['CropHeight'],$dataList[$key]['FileWidth'],$dataList[$key]['FileHeight'],$dataList[$key]['Ratio']);
            }
            $dataList = $this->mergeDataAndImage($dataList,'ContentInfo1');
            foreach ($dataList as $key=>$val){
                if(isset($val['Size'])){
                    unset($dataList[$key]['Size']);
                }
                if(isset($val['FileDescription'])){
                    unset($dataList[$key]['FileDescription']);
                }
            }
        }
        return $dataList;
    }
    
    
    function getColumnAndTagInfo($articleIds){
        if(!is_array($articleIds)){
            $articleIds = array($articleIds);
        }
        $str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
        $columnSql = "SELECT ca.ArticleID,ca.Type,cc.ColumnID,cc.ColumnName 
                    FROM cms_articles ca 
                    LEFT JOIN cms_columns cc ON ca.ColumnID=cc.ColumnID 
                    WHERE ca.ArticleID IN (".$str.")";
        $columnResult = $this->query($columnSql,$articleIds);
        $tagSql = "SELECT cat.ArticleID,cc.ColumnID,cc.ColumnName,cc.ColumnType as Type
                   FROM cms_article_tags cat 
                   LEFT JOIN cms_tags ct ON cat.TagID=ct.TagID
                   LEFT JOIN cms_columns cc on cc.TagID=ct.TagID where cc.ColumnType = 2 AND cat.ArticleID IN (".$str.") AND ct.CategoryID=15";
        $tagResult = $this->query($tagSql,$articleIds);
        $data = array();
        $columnList = array();
        while ($row = $columnResult->fetch_assoc()){
            if($columnResult->getData('ColumnID') !=1){
                $data[$columnResult->getData('ArticleID')]['Columns']['Type'] = 'column';
                $data[$columnResult->getData('ArticleID')]['Columns']['TypeID'] = $columnResult->getData('ColumnID');
                $data[$columnResult->getData('ArticleID')]['Columns']['Name'] = $columnResult->getData('ColumnName');
                $columnList[$columnResult->getData('ArticleID')] = $row;
            }
            
        }
        while ($row = $tagResult->fetch_assoc()){
            if(empty($data[$tagResult->getData('ArticleID')])){
                $data[$tagResult->getData('ArticleID')]['Columns']['Type'] = 'column';
                $data[$tagResult->getData('ArticleID')]['Columns']['TypeID'] = $tagResult->getData('ColumnID');
                $data[$tagResult->getData('ArticleID')]['Columns']['Name'] = $tagResult->getData('ColumnName');
                $columnList[$tagResult->getData('ArticleID')] = $row;
            }
        }
        foreach ($articleIds as $val){
            if(!isset($columnList[$val])){
                $columnList[$val] = array( 'ArticleID' => $val,'ColumnID' => '','ColumnName' => '','Type' => 'column');
            }
        }
        foreach ($columnList as $k=>$v){
            switch ($v['Type']){
                case 102:
                    $data[$k]['Columns']['Type'] = 'specialColumn';
                    $data[$k]['Columns']['TypeID'] = 102;
                    $data[$k]['Columns']['Name'] = '模范生';
                    break;
                case 101:
                    $data[$k]['Columns']['Type'] = 'specialColumn';
                    $data[$k]['Columns']['TypeID'] = 101;
                    $data1[$k]['Columns']['Name'] = '一周看点';
                    break;
                case 103:
                    $data[$k]['Columns']['Type'] = 'specialColumn';
                    $data[$k]['Columns']['TypeID'] = 103;
                    $data[$k]['Columns']['Name'] = '下周怎么穿';
                    break;
                case 104:
                    $data[$k]['Columns']['Type'] = 'specialColumn';
                    $data[$k]['Columns']['TypeID'] = 104;
                    $data[$k]['Columns']['Name'] = '明星穿什么';
                    break;
                case 105:
                    $data[$k]['Columns']['Type'] = 'specialColumn';
                    $data[$k]['Columns']['TypeID'] = 105;
                    $data[$k]['Columns']['Name'] = '种草';
                    break;
                case 106:
                    $data[$k]['Columns']['Type'] = 'specialColumn';
                    $data[$k]['Columns']['TypeID'] = 106;
                    $data[$k]['Columns']['Name'] = '花边';
                    break;
                case 107:
                    $data[$k]['Columns']['Type'] = 'specialColumn';
                    $data[$k]['Columns']['TypeID'] = 107;
                    $data[$k]['Columns']['Name'] = '九点';
                    break;
                case 108:
                    $data[$k]['Columns']['Type'] = 'specialColumn';
                    $data[$k]['Columns']['TypeID'] = 107;
                    $data[$k]['Columns']['Name'] = '街友评审团';
                    break;
                default:
                    if (!$v['ColumnID'] || !$v['ColumnName']) {
                        $data[$k]['Columns']['Type'] = 'column';
                        $data[$k]['Columns']['TypeID'] = 11;
                        $data[$k]['Columns']['Name'] = '时尚圈街拍';
                    }
                    break;
            }
            if ($v['Type'] == "column") {
                if ($v['ColumnID'] == 10) {
                    $data[$k]['Columns']['Name'] = "明星街拍";
                } else if ($v['ColumnID'] == 9) {
                    $data[$k]['Columns']['Name'] = "博主街拍";
                } else if ($v['ColumnID'] == 11) {
                    $data[$k]['Columns']['Name'] = "时尚圈街拍";
                }
            }
        }
        
        return $data;
    } 
    
    function getArticleStatisticTotal($articleIds,$dataList){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
        $sql = "select ArticleID,Type,OldJiepaiStatistic from cms_articles where ArticleID IN (".$str.")";
        $result = $this->query($sql,$articleIds);
        while ($row = $result->fetch_assoc()){
            if($result->getData('OldJiepaiStatistic')){
                $temp = json_decode($result->getData('OldJiepaiStatistic'));
                $dataList[$row['ArticleID']]['BrowseNum'] = (isset($dataList[$row['ArticleID']]['BrowseNum'])?intval($dataList[$row['ArticleID']]['BrowseNum']):0)+($temp->BrowseNum?intval($temp->BrowseNum):0);
                $dataList[$row['ArticleID']]['PraiseNum'] = (isset($dataList[$row['ArticleID']]['PraiseNum'])?intval($dataList[$row['ArticleID']]['PraiseNum']):0)+($temp->PraiseNum?intval($temp->PraiseNum):0);
            }
            $addBrowseNum = $dataList[$row['ArticleID']]['AddBrowseNum'] = isset($dataList[$row['ArticleID']]['AddBrowseNum'])?$dataList[$row['ArticleID']]['AddBrowseNum']:0;
            $browseNum = isset($dataList[$row['ArticleID']]['BrowseNum'])?$dataList[$row['ArticleID']]['BrowseNum']:0;
            $praiseNum = isset($dataList[$row['ArticleID']]['PraiseNum'])?$dataList[$row['ArticleID']]['PraiseNum']:0;

            $dataList[$row['ArticleID']]['BrowseNum'] = intval($browseNum) + intval($addBrowseNum);
            $dataList[$row['ArticleID']]['PraiseNum'] = intval($praiseNum) + intval($addBrowseNum);
            if (isset($articleStatisticArr[$row['ArticleID']]['PictureNum']) && ($dataList[$row['ArticleID']]['PictureNum'] > 0)) {
                $dataList[$row['ArticleID']]['PictureNum'] = $dataList[$row['ArticleID']]['PictureNum'];
            } else {
                $dataList[$row['ArticleID']]['PictureNum'] = $this->getPictureNum($row['ArticleID'],$row['Type']);
            }
        }
        return $dataList;
    }
    
    //获取文章图片数
    function getPictureNum($articleId,$type = null) {
        if(is_null($type)){
            $typeSql = "select Type from cms_articles where ArticleID=%s";
            $result = $this->query($typeSql,array($articleId))->fetch_assoc();
            if($result) $type = $result['Type'];
        }

        if($type){
            $sql = "SELECT COUNT(*) as PictureNum FROM cms_article_content WHERE ArticleID=".$articleId;
            switch ($type){
                case \haibao\jiepai\model\data\article\CmsArticles::TYPE_PICTORIAL:
                    $sql .= " AND Type in (0,4,7) ";
                    break;
                case \haibao\jiepai\model\data\article\CmsArticles::TYPE_WEEK_POINT:
                    $sql .= " AND Type in (4,9) ";
                    break;
                default :
                    $sql .= " AND Type in (4,7) ";
                    break;
            }
            $sumSql = $this->query($sql)->fetch_assoc();
            if(!empty($sumSql)){
                return intval($sumSql['PictureNum']);
            }
        }

        return 0;
    }
    
    function CheckCommentStatus($type,$typeId){
        if ($type == 1) {//评论
            $sql = "SELECT cc.Flag as flag1,ca.Flag as flag2 
                    FROM cms_comment cc LEFT JOIN cms_articles ca ON cc.TypeID = ca.ArticleID AND cc.Type = 0 WHERE cc.CommentID=%s";
        } else if ($type == 2) {//回复
            $sql = "SELECT cc.Flag as flag1,ca.Flag as flag2 
                    FROM cms_comment_reply ccr LEFT JOIN cms_comment cc ON ccr.CommentID = cc.CommentID
                    LEFT JOIN cms_articles ca ON cc.TypeID=ca.ArticleID AND cc.Type = 0
                    WHERE ccr.ReplyID = %s";
        }
        $flag = array('errorCode'=>\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::ERROR_CODE_NORMAL));
        $result = $this->query($sql,array($typeId));
        while ($result->fetch_assoc()){
            if($result->getData('flag1') == 0 && $result->getData('flag2') == 0){
                $flag = array('errorCode'=>\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::ERROR_CODE_NORMAL));
            }elseif ($result->getData('flag1') == -1){
                $flag = array('errorCode'=>\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::ERROR_CODE_COMMENT_DELETED),'errorMsg'=>'该评论已被删除');
            }else{
                $flag = array('errorCode'=>\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::ERROR_CODE_ARTICLE_DELETED),'errorMsg'=>'该文章已被删除');
            }
        }
        return $flag;
    }
    function CheckReportComment($type, $commentId, $userId){
        $sql = "SELECT COUNT(*) as count FROM cms_reports WHERE Type = %s AND TypeID = %s AND UserID =%s";
        $result = $this->query($sql,array($type, $commentId, $userId));
        $count = 0;
        while ($result->fetch_assoc()){
            $count = $result->getData('count');
        }
        return $count==0?true:false;
    }
    function ReportComments($type, $commentId, $userId){
         $sql = "INSERT INTO cms_reports (Type,TypeID,UserID,CreateTime) VALUES (%s,%s,%s,%s)";
         $this->query($sql,array($type, $commentId, $userId,new \DateTime()));
    }
    public function getArticleHotComments($articeId, $limit){

        $userList = $commentList = array();
        $userSql = "SELECT DISTINCT(UserID) from cms_comment WHERE TypeID=%s and Type=0 and Flag=0 AND AuditStatus!=2 order by Scores desc,CreateTime DESC LIMIT %s;";

        $result = $this->query($userSql, array($articeId, $limit));

        while($result->fetch_assoc()){
            $userList[$result->getData('UserID')] = $result->getData('UserID');
        }

        if($userList){
            foreach($userList as $key=>$userId){

                $sql = 'SELECT u.UserID,c.CommentID,c.Content,c.SensitiveWords,c.CreateTime,c.Scores,u.NickName,c.AuditStatus FROM cms_comment c  ' .
                    'LEFT JOIN cms_users u ON c.UserID=u.UserID ' .
                    'WHERE c.TypeID=%s AND c.Type=0 and c.UserID = %s AND c.Flag = 0 AND c.AuditStatus != 2 ORDER BY c.IsBest DESC,c.Scores DESC,c.CreateTime DESC limit 1';

                $commentInfo = $this->query($sql, array($articeId, $userId))->fetch_assoc();
                $commentInfo['Pictures'] = $this->getCommentPictures($commentInfo['CommentID']);
                array_push($commentList, $commentInfo);
            }
        }
        return $commentList;
    }

    public function getCommentPictures($commentId, $type = 1){

        $sql = "SELECT t1.TypeID,t1.PictureID FROM `cms_comment_pictures` t1 " .
            "WHERE t1.Type = %s" .
            " AND t1.TypeID = %s order by t1.Index ";

        $result = $this->query($sql, array($type, $commentId));
        $commentPicList = array();
        while($row = $result->fetch_assoc()){
            array_push($commentPicList, $row);
        }
        $commentPicList = $this->mergeDataAndImage($commentPicList, 'PictureID');
        return $commentPicList;

    }

    public function getJuryArticleInfo($articleId){
        $sql = "SELECT cac1.ContentInfo,cac2.ContentInfo as Text,ca.Type,ca.ArticleID,ca.PublishTime,ca.EndTime,ca.PublishStatus,ca.Title,cac.ContentInfo as FashionistaInfo from cms_articles ca " .
            "LEFT JOIN cms_article_content cac on ca.ArticleID=cac.ArticleID AND cac.Type=16 " .
            "LEFT JOIN cms_article_content cac1 on ca.ArticleID=cac1.ArticleID AND cac1.Type=14 " .
            "LEFT JOIN cms_article_content cac2 on ca.ArticleID=cac2.ArticleID AND cac2.Type=2 " .
            "WHERE ca.ArticleID=%s and ca.Flag=0 AND cac.Flag=0 AND cac1.Flag=0 ORDER BY cac.ShowIndex LIMIT 1;";
        $articleInfo = $this->query($sql, array($articleId))->fetch_assoc();

        if($articleInfo){
            $articleInfo = Booth::mergeOneDataAndImage($articleInfo, $articleInfo['ContentInfo']);
        }
        return $articleInfo;

    }

    //获取打分人数
    public function getJuryUserCount($articleId){
        $sql = "SELECT count(DISTINCT Type,TypeID) as count FROM cms_jury_action WHERE ArticleID=%s AND ContentIndex=1;";
        $result = $this->query($sql, array($articleId))->fetch_assoc();

        $cacheCnt = AppRedis::getHash(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::JURY_PEOPLE_COUNT_KEY).$articleId, AppRedis::JURY_COUNT);
        if($cacheCnt){
            return $result['count'] + $cacheCnt;
        }
        return $result['count'];
    }

    //获取评审团评论次数（包括删除的）
    public function getJuryCommentCount($articleId) {
        $sql = "SELECT count(*) as count FROM cms_comment WHERE Type=0 AND TypeID=%s; ";
       // $this->query($sql, array($articleId))->fetch_assoc()['count'];
    }



    // 获取一周看点文章
    public function getRecArticles($topicId,$type){

        $sql = 'SELECT t.ArticleID,a.Title,a.Type,a.PictureNum,c.ContentInfo FROM cms_articles_rec t  ' .
            'LEFT JOIN cms_articles a ON t.ArticleID=a.ArticleID ' .
            'LEFT JOIN cms_article_content c ON t.ArticleID=c.ArticleID AND c.Type=0 ' .
            'WHERE a.Flag = 0 AND t.TypeID=%s and t.Type=%s';

        $result = $this->query($sql, array($topicId, $type));
        $articleList = $dataList = array();
        while($row = $result->fetch_assoc()){
            $articleList[$result->getData('ArticleID')] = $row;
        }
        if($articleList){
            foreach ($articleList as $val){
                array_push($dataList, $val);
            }
            $dataList =  self::mergeDataAndImage($dataList);
            foreach ($dataList as $key=>$val){
                $dataList[$key]['Share'] = $val['Picture'];
            }    
        }
        return $dataList;
    }

    //获取处于时间范围内的街友评审团文章
    public function getLastJuryArticle($type = ''){
        $sql = "SELECT ca.ArticleID,ca.Type,ca.Title,ca.PublishTime,ca.EndTime,cac.ContentInfo " .
            "FROM cms_articles ca " .
            "left join cms_article_content cac on ca.ArticleID=cac.ArticleID " .
            "WHERE ca.Type=108 AND ca.PublishTime <= NOW()";
        if($type=='findings'){
            $sql .= " and cac.Type=6 ";
        }else if($type=='nineClock'){
            $sql .= " AND cac.Type=6 AND ca.EndTime > NOW()";
        }else{
            $sql .= " AND cac.Type=0 AND ca.EndTime > NOW() AND NOW() < DATE_SUB(ca.PublishTime,interval -3 day) " ;
        }
        
        $sql .= "  AND cac.Flag=0 AND ca.Flag=0 AND ca.PublishStatus=1 ORDER BY ca.PublishTime desc LIMIT 1;";

        $result = $this->query($sql)->fetch_assoc();
       
        if($result){
            return self::mergeOneDataAndImage($result, $result['ContentInfo']);
        }
        return array();
    }
    /* 获取文章是否有造型同款和造型细节标识 */
    public function getArticleOtherDetailInfo($articleList, $articleIds){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
        $sql = "SELECT ArticleID,count(*) as detailCount from cms_article_content WHERE Type=4 AND IsDetail=1 AND Flag = 0 AND ArticleID IN (".$str.") GROUP BY ArticleID";
        $goodsSql = "SELECT ArticleID,count(*) as goodsCount from cms_article_content WHERE Type=5 AND Flag=0 AND ArticleID IN (".$str.") GROUP BY ArticleID";
        $videoSql = "SELECT ArticleID,count(*) as videoCount from cms_article_content WHERE Type=12 AND Flag=0 AND ArticleID IN (".$str.") GROUP BY ArticleID";

        $result = $this->query($sql,$articleIds);
        $goodsResult = $this->query($goodsSql,$articleIds);
        $videoResult = $this->query($videoSql,$articleIds);
        $dataInfo = array('IsDetailExists'=>0,'IsGoodsExists'=>0,'IsVideoExists'=>0,'IsVoteExists'=>0);
        foreach ($articleList as $k=>$v){
            if ($v['Type'] == 108){
                $dataInfo['IsVoteExists'] = 1;
            }
            $dataList[$v['ArticleID']] = $dataInfo;
        }
        while ($result->fetch_assoc()){
            if($result->getData('detailCount')>0){
                $dataList[$result->getData('ArticleID')]['IsDetailExists'] = 1;
            }
        }
        while ($goodsResult->fetch_assoc()){
            if($goodsResult->getData('goodsCount')>0){
                $dataList[$goodsResult->getData('ArticleID')]['IsGoodsExists'] = 1;
            }
        }
        while ($videoResult->fetch_assoc()){
            if($videoResult->getData('videoCount')>0){
                $dataList[$videoResult->getData('ArticleID')]['IsVideoExists'] = 1;
            }
        }
        return $dataList;
    }
    public function getColumnLists(){
        $sql = "SELECT cc.ColumnID,cc.ColumnNameFr as NameFr,cc.ColumnType,cc.Description,cc.ColumnName as Name,cc.TitlePictureID FROM `cms_columns` cc " .
            " WHERE cc.Flag = 0 AND cc.ColumnType in (1,2) ";
        $sql .= " AND cc.ColumnID in (4,7,10,9,11,21,24) ";
        $sql .=" AND ShowIndex>0 ORDER BY cc.ShowIndex ASC ;";
        $result = $this->query($sql);

        $list = array();
        while($result->fetch_assoc()){

            $temp = array(

                'Type' => 'column',
                'TypeID' => $result->getData('ColumnID'),
                'ColumnType' => $result->getData('ColumnType'),
                'Name' => $result->getData('Name'),
                'NameFr' => $result->getData('NameFr'),
                'TitlePictureID' => $result->getData('TitlePictureID'),
            );
            array_push($list, $temp);
        }
        return self::mergeDataAndImage($list, 'TitlePictureID');
        return $list;
    }

    public function getArticleContentActions($fileId, $userId){
        $sql = "SELECT ID from cms_album_pictures where Flag = 0 AND FileID = %s AND UserID=%s";
        return count($this->query($sql, array($fileId, $userId))->fetch_assoc());
    }

    public function getArticleType($articleId){
        $sql = "SELECT Type From cms_articles Where ArticleID=%s";
        return $this->query($sql, array($articleId))->fetch_assoc();
    }

//搜索文章
    public function SearchArticle($keyword,$cursor,$version){
    	$sqlCount = "SELECT count(DISTINCT(a.ArticleID)) as count FROM `cms_articles` a ";
    	$sqlSelect = 'SELECT distinct a.ArticleID,a.PublishTime,a.Type,a.Title,c.ContentInfo FROM cms_articles a ';
    	$sql = 	'LEFT JOIN cms_article_content c ON a.ArticleID=c.ArticleID AND c.Type=0 ' ;
    	if (self::ComputeVersion($version) >= self::ComputeVersion(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_430))) {
    		$sql .= ' WHERE a.Type in (1,2,101,102,103,104,105,106,108) ';
    	} else if (self::ComputeVersion($version) >= self::ComputeVersion(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_420))) {
    		$sql .= ' WHERE a.Type in (1,2,101,102,103,104,105,106) ';
    	} else {
    		$sql .= ' WHERE a.Type in (1,2) ';
    	}
    	$sql .= 'AND a.PublishTime < NOW() AND a.Flag=0 and a.PublishStatus=1 AND (a.Title LIKE %s OR a.TagList LIKE %s ) ';
    	if ($cursor) {
    		$sql .= "AND a.PublishTime < '" . date('Y-m-d H:i:s',intval($cursor)) . "'";
    	}
    	$list = array();
    	$arr = $this->query($sqlCount . $sql,array('%'.$keyword.'%','%'.$keyword.'%###'))->fetch_assoc();
    	$list['count'] = $arr['count'];
    	
    	$sql .= ' ORDER BY a.PublishTime DESC LIMIT '. (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE) + 1);

    	$result = $this->query($sqlSelect.$sql,array('%'.$keyword.'%','%'.$keyword.'%###'));
    	while($row = $result->fetch_assoc()){
    		$list[] = $row;
    	}
    	return $list;

    }

    /**
     * 计算版本号，例如4.4.0返回4004000
     * @param $version
     * @return int
     */
    public static function ComputeVersion($version)
    {
    	if (!$version) {
    		return 0;
    	}
    	$versionNumber = explode('.', $version);
    	array_map('intval', $versionNumber);
    	return ($versionNumber[0] ? $versionNumber[0] : 0) * 1000000 + ($versionNumber[1] ? $versionNumber[1] : 0) * 1000 + ($versionNumber[2] ? $versionNumber[2] : 0) * 1;
    }
    //获取首页插入的特殊类别字段，在cms_focus_material表中
    public function getHomeAllSpecialArticles(){
        $sql = "SELECT t1.UpIndex,t1.Type,t1.TypeID as ArticleID,t1.Title,t1.Link,t1.UpIndex 
         FROM cms_focus_material t1 
         LEFT JOIN cms_articles ca on ca.ArticleID=t1.TypeID  
         LEFT JOIN cms_article_content cac on ca.ArticleID=cac.ArticleID 
         WHERE t1.UpIndex in (2,6) AND ca.PublishTime <= '".date('Y-m-s H:i:s')."' AND cac.Type=0 AND ca.Flag = 0 AND ca.PublishStatus=1 AND cac.Flag = 0 AND t1.Category = 2 AND t1.Flag = 0 AND (t1.UpTime < '".date('Y-m-s H:i:s')."' AND (t1.DownTime > '".date('Y-m-s H:i:s')."' OR t1.DownTime = '0000-00-00 00:00:00')) GROUP BY t1.UpIndex ORDER BY t1.UpTime DESC";
        $result = $this->query($sql);
        $dataList = array();
        while ($row = $result->fetch_assoc()){
            $dataList[$result->getData('ArticleID')] = $row;
        }
        return $dataList;
    }
    //获取信息流和头条文章ID
    public function getHeadLineArticles(){
        $sql = "SELECT TypeID as ArticleID 
            FROM cms_focus_material 
            WHERE Category in (2,3) AND Type=1 AND UpTime<='".date('Y-m-d H:i:s')."' and (DownTime>'".date('Y-m-d H:i:s')."' OR DownTime='0000-00-00 00:00:00' OR DownTime='') AND Flag=0";
        $result = $this->query($sql);
        $dataList = array();
        while ($result->fetch_assoc()){
            $dataList[]['ArticleID'] = $result->getData('ArticleID');
        }
        return $dataList;
    }
    
    public function getArticleHomeColumnGuidance($type, $unInvolved){
        $sql = "SELECT ca.ArticleID,ca.Type,ca.Title,cac.ContentInfo FROM cms_articles ca 
                LEFT JOIN cms_article_content cac on ca.ArticleID=cac.ArticleID 
                WHERE cac.Type=6 AND ca.Type=1 AND ColumnID=".$type." AND ca.Flag=0 AND ca.PublishStatus=1 AND ca.PublishTime <= NOW() AND cac.Flag=0 ";
        if ($unInvolved && count($unInvolved) > 0) {
            $str = preg_replace('/(\d+)/', '%s', implode(',', $unInvolved));
            $sql .= " AND ca.ArticleID NOT IN (" .$str. ") ";
        }
        $sql .= " ORDER BY ca.PublishTime desc LIMIT 6;";
        $dataList = array();
        if(count($unInvolved)>0){
            $result = $this->query($sql,$unInvolved);
        }else{
            $result = $this->query($sql);
        }
        while ($row = $result->fetch_assoc()){
            array_push($dataList, $row);
        }
        if($dataList){
            $dataList = $this->mergeDataAndImage($dataList,'ContentInfo');
        }
        return $dataList;
    }
    //编辑账号查看预发布的文章
    function GetAuthorArticles($userId) {
        $dataList = array();
        if ($userId) {
            $isAuthor = $this->IsEditor($userId);
            if($isAuthor>0){
                $this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_STREET_SNAP_DB);
                $selectSql = 'SELECT ';
                $otherSql = 'FROM cms_articles a
                LEFT JOIN cms_article_content c on a.ArticleID=c.ArticleID AND c.Type=0 
                LEFT JOIN cms_article_content c2 on a.ArticleID=c2.ArticleID AND c2.Type=6';
                
                $selectSql .= ' a.ArticleID,a.PublishTime,a.Title,a.Type,a.PictureNum,
                a.ContentLink,c.ContentInfo as ContentInfo1,c2.ContentInfo as ContentInfo2 ';
                
                $otherSql .= ' LEFT JOIN cms_columns m on a.ColumnID=m.ColumnID 
                  WHERE (m.Flag =0 OR m.Flag = null) and a.Flag=0  AND a.PublishStatus = 1 AND ';
                
                $otherSql .= ' a.Type in (1,2,101,102,103,104,105,106,108) ';
                $otherSql .= ' AND a.PublishTime > NOW() ';
                $otherSql .= " ORDER BY a.PublishTime DESC ";
                $sql = $selectSql . $otherSql;
                $result = $this->query($sql);
                while ($row = $result->fetch_assoc()){
                    $dataList[$result->getData('ArticleID')] = $row;
                }
                if($dataList){
                    $dataList = $this->mergeDataAndImage($dataList,'ContentInfo2');
                    foreach ($dataList as $key=>$val){
                        $dataList[$key]['Picture2'] = $val['Picture'];
                        $dataList[$key]['CropX2'] = $val['CropX'];
                        $dataList[$key]['CropY2'] = $val['CropY'];
                        $dataList[$key]['CropWidth2'] = $val['CropWidth'];
                        $dataList[$key]['CropHeight2'] = $val['CropHeight'];
                        $dataList[$key]['FileWidth2'] = $val['FileWidth'];
                        $dataList[$key]['FileHeight2'] = $val['FileHeight'];
                        $dataList[$key]['Ratio2'] = $val['Ratio'];
                        unset($dataList[$key]['Picture'],$dataList[$key]['CropX'],$dataList[$key]['CropY'],$dataList[$key]['CropWidth'],$dataList[$key]['CropHeight'],$dataList[$key]['FileWidth'],$dataList[$key]['FileHeight'],$dataList[$key]['Ratio']);
                    }
                    $dataList = $this->mergeDataAndImage($dataList,'ContentInfo1');
                    foreach ($dataList as $key=>$val){
                        if(isset($val['Size'])){
                            unset($dataList[$key]['Size']);
                        }
                        if(isset($val['FileDescription'])){
                            unset($dataList[$key]['FileDescription']);
                        }
                    }
                }
            }
        }
        return $dataList;
    }
    /* 查看是否是编辑账号 */
    function IsEditor($userId) {
        $count = 0;
        if ($userId) {
            $this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
            $sql = 'SELECT count(*) as count FROM `Guise` WHERE GuiseId=%s';
            $result = $this->query($sql,array($userId));
            while ($result->fetch_assoc()){
                $count = $result->getData('count');
            }
        }
        return $count;
    }
    //获取首页第一篇文章ID号
    public function getFirstArticleID(){
        $sql = "SELECT ArticleID FROM cms_articles WHERE Flag=0 and PublishStatus=1 and ";
        $sql .= " Type in (1,2,101,102,103,104,105,106) ";
        $sql .= " AND PublishTime < NOW() order by PublishTime desc limit 1;";
        return $this->query($sql)->fetch_assoc();
    }


    public function GetWidgetArticles(){
    	$mixedSql = "SELECT ca.ArticleID,ca.Title,ca.Type,cac.ContentInfo as Picture FROM cms_articles ca LEFT JOIN cms_article_content cac ON ca.ArticleID=cac.ArticleID" .
    			" WHERE ca.PublishStatus = 1 AND ca.Flag=0 AND ca.PublishTime <=NOW() AND ca.Type in (1,101,102,103,104,105,106) AND cac.Type=6 AND cac.Flag=0 ORDER BY ca.PublishTime desc LIMIT 2;";

    	$pictorialSql = "SELECT ca.ArticleID,ca.Title,ca.Type,cac.ContentInfo as Picture FROM cms_articles ca LEFT JOIN cms_article_content cac ON ca.ArticleID=cac.ArticleID" .
    			" WHERE ca.PublishStatus = 1 AND ca.Flag=0 AND ca.PublishTime <=NOW() AND ca.Type=2 AND cac.Type=0 AND cac.Flag=0 ORDER BY ca.PublishTime desc LIMIT 3;";
    	$result = array();
    	$resultMixed = $this->query($mixedSql);
    	$resultPictorial = $this->query($pictorialSql);
    	$i = $j =0;
    	while ($row = $resultMixed->fetch_assoc()){
    		$result['mixedArticles'][$i]['ArticleID'] = $row['ArticleID'];
    		$result['mixedArticles'][$i]['Type'] = $row['Type'];
    		$result['mixedArticles'][$i]['Title'] = $row['Title'];
    		$result['mixedArticles'][$i]['Picture'] = $row['Picture'];
    		$result['mixedArticles'][$i]['Ratio'] = 3;
    		$i++;
    	}
    	while ($row = $resultPictorial->fetch_assoc()){
    		$result['pictorialArticles'][$j]['ArticleID'] = $row['ArticleID'];
    		$result['pictorialArticles'][$j]['Type'] = $row['Type'];
    		$result['pictorialArticles'][$j]['Title'] = $row['Title'];
    		$result['pictorialArticles'][$j]['Picture'] = $row['Picture'];
    		$result['pictorialArticles'][$j]['Ratio'] = 2;
    		$j++;
    	}
    	return $result;
    }

    public function ClearVisitorByDeviceID($deviceId){
    	$sql = 'update cms_visitors set Flag=-1 where DeviceID=%s';
    	$this->query($sql,array($deviceId));
    	return true;
    }

    public function CreateVisitor($modelArr){
    	$list = array();
    	$datatime = new \DateTime();
    	$sql = "INSERT INTO cms_visitors(CreateTime,DeviceID,DeviceType,DeviceCategory,DeviceOsVersion,Flag) values (%s,%s,%s,%s,%s,0)";
    	$this->query($sql,array($datatime,$modelArr['DeviceID'],$modelArr['DeviceType'],$modelArr['DeviceCategory'],$modelArr['DeviceOsVersion']));
    	$insertId = $this->getDb()->insert_id;
    	return $insertId;
    }

    public function getJuryArticleIDList(){

        $sql = "SELECT ArticleID FROM cms_articles WHERE PublishTime<NOW() AND PublishStatus=1 AND Flag=0 AND EndTime<NOW() ORDER BY PublishTime desc; ";
        $result = $this->query($sql);
        $articlIds = array();
        while($result->fetch_assoc()){
            array_push($articlIds, $result->getData('ArticleID'));
        }
        return $articlIds;
    }
    public function getPrevJuryArticle($publishTime){
        $sql = "SELECT PublishTime,EndTime,ArticleID FROM cms_articles WHERE Flag=0 AND Type=108 AND PublishStatus=1 AND PublishTime<%s order by PublishTime desc LIMIT 1;";
        return $this->query($sql, array($publishTime))->fetch_assoc();
    }

    public function getIsJuryArticle($articleId, $userId, $visitorId){

        $sql = "SELECT count(*) as count From cms_jury_action WHERE ArticleID=%s AND Type=%s AND TypeID=%s AND Flag=0;";
        $arr = array();
        array_push($arr, $articleId);
        $userId>0?array_push($arr, 1):array_push($arr, 2);
        $userId>0?array_push($arr, $userId):array_push($arr, $visitorId);
        $result = $this->query($sql, $arr)->fetch_assoc();
        return $result?$result['count']:0;
    }
    public function getJuryArticleFashionistaList($articleId){
        $sql = "SELECT ContentInfo from cms_article_content WHERE ArticleID=%s AND Type=16 AND Flag=0 ORDER BY ShowIndex ASC;";
        $result = $this->query($sql,array($articleId));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return $list;

    }
    //获取实际打分人数
    public function getRealJuryUserCount($articleId){
        $sql = "SELECT count(DISTINCT Type,TypeID) as count FROM cms_jury_action WHERE ArticleID=%s AND Flag=0 AND ContentIndex=1";
        $result = $this->query($sql,array($articleId));
        $count = 0;
        while ($result->fetch_assoc()){
            $count = $result->getData('count');
        }
        return $count;
    }
    
    //获取最受欢迎人物信息
    function getJuryHighest($articleId) {
        $sql = "SELECT ContentIndex,count(DISTINCT Type,TypeID) as count FROM cms_jury_action WHERE ArticleID=%s AND IsLike=1 AND ContentIndex>=1 AND ContentIndex<=7 GROUP BY ContentIndex ORDER BY count desc LIMIT 1";
        $result = $this->query($sql,array($articleId));
        return $result->fetch_assoc();
    }
    
    //获取文章瀑布流题图
    function getArticleTitlePicture($articleId) {
        $sql = "SELECT ca.ArticleID,cac.ContentInfo FROM cms_articles ca 
        LEFT JOIN cms_article_content cac ON ca.ArticleID=cac.ArticleID 
         WHERE ca.ArticleID=%s AND (CASE ca.Type WHEN 4 THEN cac.Type=4 
         ELSE cac.Type=0 END) ";
        $result = $this->query($sql,array($articleId));
        $dataList = $result->fetch_assoc();
        if($dataList){
            $dataList = self::mergeOneDataAndImage($dataList, $dataList['ContentInfo']);
        }
       return $dataList;
    }
    
    /* 获取街友评审团人物打分情况 */
    function getJuryFashionistaPoints($articleId, $contentIndex) {
        $sql = "SELECT ContentIndex,COUNT(DISTINCT Type,TypeID) as count FROM cms_jury_action WHERE Flag=0 AND IsLike=1 AND ArticleID=%s AND ContentIndex=%s";
        $result = $this->query($sql,array($articleId, $contentIndex));
        $count = 0;
        while ($result->fetch_assoc()){
            $count =$result->getData('count'); 
        }
        return $count;
    }
    
    //获取评审团优选评论
    function getBestCommentUsers($articleId) {
        $sql = "SELECT cc.UserID,cu.AvatarID,cu.NickName FROM cms_comment cc
            LEFT JOIN cms_users cu on cc.UserID=cu.UserID 
            WHERE cc.Type=0 AND cc.TypeID=%s AND cc.IsBest=1 AND cc.Flag=0 AND cc.AuditStatus!=2 GROUP BY cc.UserID ";
        $result = $this->query($sql,array($articleId));
        $dataList = array();
        while ($row = $result->fetch_assoc()){
            array_push($dataList, $row);
        }
        return $dataList;
    }
    /* 获取评审团打分是否喜欢 */
    function getJuryArticleFashionistaIsLike($contentIndex, $articleId, $userId, $visitorId){
        $sql = "SELECT count(*) as count FROM cms_jury_action WHERE ContentIndex=%s AND ArticleID=%s AND Type=%s AND TypeID=%s AND Flag=0 AND IsLike=1";
        $resutl = $this->query($sql,array($contentIndex, $articleId, ($userId>0)?1:2, ($userId > 0) ? $userId : $visitorId));
        $count = 0;
        while ($resutl->fetch_assoc()){
            $count = $resutl->getData('count');
        }
        return $count;
    }
    /* 获取评审团都不喜欢的人数 */
    function getJuryArticleUnLikePeopleCount($articleId,$isSpecial){
        $num = 7;
        if ($isSpecial){
            $num = 20;
        }
        $sql = "SELECT count(*) as count from (SELECT DISTINCT Type,TypeID FROM `cms_jury_action` WHERE ArticleID=%s AND IsLike = 0 AND Flag=0 GROUP BY Type,TypeID HAVING count(*)>=".$num.") a";
        $result = $this->query($sql,array($articleId));
        $count = 0;
        while ($result->fetch_assoc()){
            $count = $result->getData('count');
        }
        return $count;
    }
    /* 获取评审团评论列表(周期结束后) */
    function getJuryComments($articleId, $contentIndex, $IsBest){
        $sql = "SELECT t1.CommentID,t1.Scores,t1.Content,t1.SensitiveWords,t1.UserID,t1.CreateTime,t2.NickName,t1.AuditStatus FROM cms_comment t1 
        LEFT JOIN cms_users t2 on t1.UserID = t2.UserID 
        WHERE t1.TypeID = %s AND ContentIndex=%s AND t1.Type = 0 AND t1.Flag = 0 AND t1.AuditStatus != 2 AND IsBest=%s ORDER BY t1.IsBest desc ";
        if ($IsBest == 1) {
            $sql .= ",t1.Scores desc";
        }
        $sql .= ",t1.CreateTime desc";
        $result = $this->query($sql,array($articleId, $contentIndex, $IsBest));
        $dataList = array();
        while ($row = $result->fetch_assoc()){
            array_push($dataList, $row);
        }
        return $this->resolveComment($dataList);
    }
    public function getLastestNineClockArticle(){
        $sql = "SELECT ArticleID FROM cms_articles WHERE Type=107 AND Flag=0 AND PublishTime <= NOW() AND PublishStatus=1 ORDER BY PublishTime desc LIMIT 1;";
        $result = $this->query($sql)->fetch_assoc();
        return $result?$result['ArticleID']:NULL;

    }

    public function getArticleInfoById($articleId){

        if(is_array($articleId)){
            $str = preg_replace('/(\d+)/','%s',implode(',', $articleId));
            array_push($articleId, implode(',', $articleId));
            $sql = 'SELECT a.SubtitleType as KeyTitle,a.Subtitle as KeyWord,a.ArticleID,a.Title,a.Type,a.CreateTime,a.PublishTime,c.ContentInfo,a.ColumnID ' .
                'FROM cms_articles a ' .
                'INNER JOIN cms_article_content c on a.ArticleID=c.ArticleID and c.Type=0 ' .
                'WHERE a.ArticleID in ('.$str.') order by find_in_set(a.ArticleID, %s)';
            $result = $this->normalQuery($sql, $articleId);
            if($result){
                return self::mergeDataAndImage($result);
            }
        }else{

            $sql = 'SELECT a.SubtitleType as KeyTitle,a.Subtitle as KeyWord,a.ArticleID,a.Title,a.Type,a.CreateTime,a.PublishTime,c.ContentInfo,a.ColumnID ' .
                'FROM cms_articles a ' .
                'INNER JOIN cms_article_content c on a.ArticleID=c.ArticleID and c.Type=0 ' .
                'WHERE a.ArticleID=%s';
            $result = $this->query($sql, array($articleId))->fetch_assoc();
            if($result){
                return self::mergeOneDataAndImage($result, $result['ContentInfo']);
            }
        }
        return array();
    }

    public function getNineClockArticleContent($articleId){

        // 获取文章内容为4.图片，6.信息流题图
        $finalContent = array();
        $sql = 'SELECT c.ShowIndex,c.ID AS ContentID,c.Type,c.ContentInfo AS Text FROM cms_article_content c where (c.Type = 6 OR c.Type = 4) AND c.ArticleID = %s AND c.Type != 0 AND c.Flag = 0';
        $result = $this->query($sql,array($articleId));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        if($list){
            $finalContent = self::mergeDataAndImage($list, 'Text');
        }

        // 获取文章内容为11.音频
        $sql = 'SELECT c.ShowIndex,c.ID AS ContentID,c.Type,c.ContentInfo AS Text,m.Title AS AudioTitle,m.Title AS AudioName,m.Singer,m. NAME AS Song,m.`Cover` FROM cms_article_content c LEFT JOIN cms_media_files m ON c.ContentInfo = m.MediaID WHERE c.Type = 11 AND c.ArticleID = %s AND c.Type != 0 AND c.Flag = 0';
        $result = $this->query($sql,array($articleId));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        if($list){
            $list = self::mergeDataAndImage($list, 'Cover');
            foreach($list as $key=>&$item){
                $item['AudioPicture'] = $item['Picture'];
                unset($list[$key]['Picture']);
            }
            $finalContent = array_merge($finalContent, $list);
        }

        $list = array();
        // 获取文章内容为9.文章
        $sql = 'SELECT
                    c.ShowIndex,
                    c.Type,
                    c1.ContentInfo AS Text,
                    ca.Title AS Title,
                    ca.Type AS ArticleType,
                    ca.ArticleID,
                    c.ContentInfo
                FROM
                    cms_article_content c
                LEFT JOIN cms_articles ca ON c.ContentInfo = ca.ArticleID
                LEFT JOIN cms_article_content c1 ON ca.ArticleID = c1.ArticleID
                AND (c1.Type = 6)
                WHERE
                c.ArticleID = %s
                AND c.Type != 0
                AND c.Flag = 0 And c.Type in (9,10)
                ORDER BY
                    c.ShowIndex ASC';

        $result = $this->query($sql,array($articleId));
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        if($list){
            $list = self::mergeDataAndImage($list, 'Text');
            /*$tempArr = array();
            foreach($list as $key=>$item){
                $temp = array();
                $temp['ArticlePicture'] = $item['Picture'];
                $temp['ArticleRatio'] = $item['Ratio'];
                $temp['ArticleFileWidth'] = $item['FileWidth'];
                $temp['ArticleFileHeight'] = $item['FileHeight'];
                $temp['ArticleCropX'] = $item['CropX'];
                $temp['ArticleCropY'] = $item['CropY'];
                $temp['ArticleCropWidth'] = $item['CropWidth'];
                $temp['ArticleCropHeight'] = $item['CropHeight'];
                $temp['ShowIndex'] = $item['ShowIndex'];
                $temp['ContentID'] = $item['ContentID'];
                $temp['Type'] = $item['Type'];
                $temp['Text'] = $item['Text'];
                array_push($tempArr, $temp);
            }*/
            $finalContent = array_merge($finalContent, $list);
        }
        return $finalContent;

        // 获取文章内容为6.信息流题图
        /*$sql = 'SELECT c.ShowIndex,c.ID AS ContentID,c.Type,c.ContentInfo AS Text FROM cms_article_content c where c.Type = 6 AND c.ArticleID = %s AND c.Type != 0 AND c.Flag = 0';
        $result = $this->query($sql,array($articleId));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }*/
        $list = array();

        if($list){
            $list = self::mergeDataAndImage($list, 'Text');
            $tempArr = array();
            foreach($list as $key=>$item){
                $temp = array();
                $temp['ArticlePicture'] = $item['Picture'];
                $temp['ArticleRatio'] = $item['Ratio'];
                $temp['ArticleFileWidth'] = $item['FileWidth'];
                $temp['ArticleFileHeight'] = $item['FileHeight'];
                $temp['ArticleCropX'] = $item['CropX'];
                $temp['ArticleCropY'] = $item['CropY'];
                $temp['ArticleCropWidth'] = $item['CropWidth'];
                $temp['ArticleCropHeight'] = $item['CropHeight'];
                $temp['ShowIndex'] = $item['ShowIndex'];
                $temp['ContentID'] = $item['ContentID'];
                $temp['Type'] = $item['Type'];
                $temp['Text'] = $item['Text'];
                array_push($tempArr, $temp);
            }
            $finalContent = array_merge($finalContent, $tempArr);
        }
        return $finalContent;
    }

    public function getArticleFirstTextContent($articleId, $type=2){
        $sql = "SELECT ContentInfo FROM cms_article_content WHERE ArticleID=%s AND Type=%s AND Flag=0 ORDER BY ShowIndex asc LIMIT 1;";
        $content = '';
        $query = $this->query($sql,array($articleId, $type))->fetch_assoc();
        if($query && $query['ContentInfo']){
            $content = preg_replace('/(<a|<\/a)(.*?)>/', '', $query['ContentInfo']);
        }
        return $content;
    }

    public function getArticleHaveVideo($articleId){
        $sql = "SELECT count(*) as count from cms_article_content WHERE Flag=0 AND Type=12 and ArticleID=%s;";
        $result = $this->query($sql, array($articleId))->fetch_assoc();
        return $result?$result['count']:0;
    }
    /* 获取评审团评论列表(周期内) */
    public function getJuryDuringComments($articleId,$contentIndex){
       $sql = "SELECT t1.CommentID,t1.Scores,t1.Content,t1.SensitiveWords,t1.UserID,t1.CreateTime,t2.NickName,t1.AuditStatus FROM cms_comment t1 
        LEFT JOIN cms_users t2 on t1.UserID = t2.UserID 
        WHERE t1.TypeID = %s AND ContentIndex=%s AND t1.Type = 0 AND t1.Flag = 0 AND t1.AuditStatus != 2 
        ORDER BY 
        CASE 
        WHEN t1.IsBest=1 THEN  t1.IsBest 
        END desc,
        CASE 
        WHEN t1.IsBest=1 THEN t1.Scores 
        END desc,
        t1.CreateTime desc";
        $result = $this->query($sql,array($articleId, $contentIndex));
        $dataList = array();
        while ($row = $result->fetch_assoc()){
            array_push($dataList, $row);
        }
        return $this->resolveComment($dataList);
    }
    public function resolveComment($results){
        $commentArr = array();
        if($results){
            foreach ($results as $k=>$v){
                array_push($commentArr, array(
                'CommentID'=>$v['CommentID'],
                'Content'=>$v['Content'],
                'CreateTime'=> $v['CreateTime'],
                'Scores'=> $v['Scores'],
                'AuditStatus'=> $v['AuditStatus'],
                'SensitiveWords'=> $v['SensitiveWords'],
                'IsPraise'=> 0,
                'User'=> array('UserID'=>$v['UserID'],'NickName'=>$v['NickName'],'Avatar'=>'')
                ));
            }
        }
        return $commentArr;
    }
    
    public function setHotCommentStatistic($dataList, $userId) {
        foreach ($dataList as $k=>$v){
            if(!isset($v['ReplyID']) && $v['CommentID']){
                $sql1 = "SELECT count(*) as PraiseNum FROM cms_user_action WHERE Type = 3 and Flag = 0 AND TypeID = %s";
                $sql2 = "SELECT count(*) as ReplyNum From cms_comment_reply WHERE CommentID =%s AND AuditStatus !=2 AND Flag = 0;";
                $results1 = $this->query($sql1,array($v['CommentID']));
                $results2 = $this->query($sql2,array($v['CommentID']));
                $dataList[$k]['Statistic']['PraiseNum'] = 0;
                $dataList[$k]['Statistic']['ReplyNum'] = 0;
                while ($results1->fetch_assoc()){
                    $dataList[$k]['Statistic']['PraiseNum'] = $results1->getData('PraiseNum')?$results1->getData('PraiseNum'):0;
                }
                while ($results2->fetch_assoc()){
                    $dataList[$k]['Statistic']['ReplyNum'] = $results2->getData('PraiseNum')?$results2->getData('PraiseNum'):0;
                }
                if($userId){
                    $dataList[$k]['IsPraise'] = $this->getCommentUserActions($v['CommentID'],$userId);
                }
            }
        }
        return $dataList;
    }
    public function getCommentUserActions($commentId, $userId){
        $results = \haibao\jiepai\business\User::getUserActions(3, $commentId, $userId);
        return count($results);
    }
    public function gtLastDuringJuryArticle(){

        $sql = "SELECT ca.ArticleID,ca.Type,ca.Title,cac.ContentInfo " .
            "FROM cms_articles ca " .
            "left join cms_article_content cac on ca.ArticleID=cac.ArticleID " .
            "WHERE ca.Type=108 AND ca.PublishTime <= NOW() AND ca.EndTime>NOW() AND cac.Type=6 AND cac.Flag=0 AND ca.Flag=0 AND ca.PublishStatus=1 ORDER BY ca.PublishTime desc LIMIT 1;";
        $result = $this->query($sql)->fetch_assoc();
        if($result){
            return self::mergeOneDataAndImage($result, $result['ContentInfo']);
        }
        return array();
    }

    public function getJuryCursor($articleId){
        $sql = "SELECT PublishTime FROM cms_articles WHERE Type=108 AND ArticleID=%s;";
        $publishTime = $this->query($sql,array($articleId))->fetch_assoc();

        $prevSql = "SELECT ArticleID FROM cms_articles WHERE Type=108 AND PublishTime<%s AND PublishTime<NOW() AND EndTime<NOW() AND PublishStatus=1 AND Flag=0 ORDER BY PublishTime desc limit 1;";
        $prevJury = $this->query($prevSql, array($publishTime['PublishTime']))->fetch_assoc();

        $nextSql = "SELECT ArticleID FROM cms_articles WHERE Type=108 AND PublishTime>%s AND PublishTime<NOW() AND EndTime<NOW() AND PublishStatus=1 AND Flag=0 ORDER BY PublishTime asc limit 1;";
        $nextJury = $this->query($nextSql, array($publishTime['PublishTime']))->fetch_assoc();

        return array(($prevJury)?$prevJury['ArticleID']:0, ($nextJury)?$nextJury['ArticleID']:0);
    }

    public function getJuryArticleTotalNum(){
        $sql = "SELECT count(*) as count FROM cms_articles WHERE PublishTime<NOW() AND PublishStatus=1 AND Flag=0 AND EndTime<NOW();";
        $result = $this->query($sql)->fetch_assoc();
        return $result?$result['count']:0;

    }

    public function getJuryArticleIndex($articleId){
        $sql = "SELECT rowNum from (SELECT ArticleID,(@rowNum:=@rowNum+1) as rowNum  from cms_articles,(Select (@rowNum :=0) ) b WHERE " .
            " PublishStatus=1 AND Flag=0 AND Type=108 " .
            " ORDER BY PublishTime ASC ) c  WHERE c.ArticleID=%s";

        $result = $this->query($sql, array($articleId))->fetch_assoc();
        return $result?$result['rowNum']:1;
    }
    //获取编辑账号马甲信息
    public function getArticleAuthorInfo($articleId,$userId){
        $results  = array();
        if($userId !=0){
            $guise = new \haibao\cms\data\Guise();
            $isEditor = $guise->getGuiseInfoByGuiseId((int)$userId);
            if($isEditor){
                $results['IsAuthor'] = $this->isArticleAuthor($articleId,$userId);
                $results['Editors'] = $this->getArticleAuthorList($userId);
                $user = array();
                if($results['Editors']){
                    $user  = array_filter($results['Editors'],function($editor)use($userId){
                        return $editor['UserID'] == $userId;
                    });
                    $results['Editors']  = array_filter($results['Editors'],function($editor)use($userId){
                        return $editor['UserID'] != $userId;
                    });
                }
                $results['Editors'] = array_merge($results['Editors'], ($results['IsAuthor'])?array(array('UserID'=>$userId,'NickName'=>'作者回复','Avatar'=>'')):((count($user) > 0)?array($user[0]):array())) ;
            }
        }
        return $results;
    }
    //判断账号是否是文章作者
    public function isArticleAuthor($articleId,$userId){
        $sql = "SELECT count(*) as count FROM cms_articles WHERE ArticleID=%s AND EditorID=%s ";
        $result = $this->query($sql,array($articleId,$userId));
        $count = 0;
        while ($result->fetch_assoc()){
            $count = $result->getData('count');
        }
        return $count;
    }
    //获取作者马甲列表
    public function getArticleAuthorList($userId){
        $this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
        $sql = 'SELECT * FROM `Guise` WHERE GuiseId=%s';
        $result = $this->query($sql,array($userId));
        $dataList = array();
        while ($result->fetch_assoc()){
           array_push($dataList, array('UserID'=>$result->getData('UserId'),'NickName'=>$result->getData('Nickname'),'Avatar'=>''));
        }
//        $sql = "SELECT cu.UserID,cu.NickName,cf.ServerFileName as Avatar from cms_admin_users cau 
//         INNER JOIN cms_users cu on cau.UserID=cu.UserID
//         INNER JOIN cms_files cf on cu.AvatarID=cf.FileID 
//         WHERE Type='P' AND AdminID IN (SELECT AdminID FROM cms_admin_users WHERE UserID=%s) ";
       return $dataList;
    }

    public function getArticle($articleId) {
        $sql = 'SELECT a.SubtitleType as KeyTitle,a.Subtitle as KeyWord,a.ArticleID,a.Title,a.Type,a.CreateTime,a.PublishTime,c.ContentInfo,a.ColumnID
        FROM cms_articles a 
        LEFT JOIN cms_article_content c on a.ArticleID=c.ArticleID and c.Type=0 
        WHERE a.ArticleID=%s';
        $result =  $this->query($sql,array($articleId));
        $dataList = array();
        while ($row = $result->fetch_assoc()){
            array_push($dataList, $row);
        }
        if($dataList){
            return self::mergeDataAndImage($dataList, 'ContentInfo');
        }
        return array();
    }
    /* type 6 为信息流题图 */
    public function getArticleContents($articleId){
//       $sql1 = 'SELECT c.ID as ContentID,c.Type,c.ContentInfo as Text,
//           f.FileSize,f.FileID,f.ShareFileName as Share,f.Description as FileDescription,f.ServerFileName as Picture,
//           f.CropX,f.CropY,f.CropWidth,f.CropHeight,f.Ratio,f.FileWidth,f.FileHeight,
//           g.GoodsID,g.GoodsName,g.Price,f1.ServerFileName as GoodsPicture, c.IsDetail,c.IsOriginal,g.Currency,t.TagName as GoodsBrand,
//           f1.Ratio as GoodsRatio,f1.ShareFileName as GoodsShare,f1.FileWidth as GoodsWidth,f1.FileHeight as GoodsHeight,f1.CropX as GoodsCropX,f1.CropY as GoodsCropY,f1.CropWidth as GoodsCropWidth, f1.CropHeight as GoodsCropHeight,g.GoodsLink,g.IsBlocked as IsGoodsLinkBlocked, 
//           m.Title as AudioTitle, f2.ServerFileName as AudioPicture,m1.Title as VideoTitle,f3.ServerFileName as VideoPicture,f3.FileWidth as VideoPictureWidth,f3.FileHeight as VideoPictureHeight,
//           m1.Description as VideoDescription,m1.Name as VideoLink  
//         FROM cms_article_content c  
//         LEFT JOIN cms_files f ON c.ContentInfo=f.FileID AND (c.Type=0 OR c.Type=4)  
//         LEFT JOIN cms_goods g ON c.ContentInfo=g.GoodsID AND c.Type=5   
//         LEFT JOIN cms_tags t on g.GoodsBrand = t.TagID  
//         LEFT JOIN cms_files f1 ON g.FileID=f1.FileID 
//         LEFT JOIN cms_media_files m on c.ContentInfo=m.MediaID AND m.Type=1 
//         LEFT JOIN cms_files f2 ON m.Cover=f2.FileID  
//         LEFT JOIN cms_media_files m1 on c.ContentInfo=m1.MediaID AND m1.Type=2 
//         LEFT JOIN cms_files f3 ON m1.Cover=f3.FileID  
//          WHERE c.ArticleID=%s AND c.Type != 6 AND c.Flag = 0 ORDER BY c.ShowIndex asc';
      
//       $allResult = $this->query($sql1,array($articleId));
//       $dataList1 = array();
      
//       while ($row = $allResult->fetch_assoc()){
//           array_push($dataList1, $row);
//       }
      $articleContent =array();
      $sql = 'SELECT c.ID as ContentID,c.Type,c.ContentInfo as Text,c.IsDetail,c.IsOriginal,c.ContentInfo as FileID,c.ShowIndex FROM cms_article_content c  
               WHERE c.ArticleID=%s AND c.Type NOT IN (0,4,5,6,11,12) AND c.Flag = 0 ORDER BY c.ShowIndex asc';
      $allResult = $this->query($sql,array($articleId));
      while ($row = $allResult->fetch_assoc()){
          array_push($articleContent, $row);
      }
      if($articleContent){
          foreach($articleContent as $key=>$model){
              $articleContent[$key]['FileID'] = 0;
          }    
      }
      
      $sql = 'SELECT c.ID as ContentID,c.Type,c.ContentInfo as Text,c.IsDetail,c.IsOriginal,c.ContentInfo as FileID,c.ShowIndex
              FROM cms_article_content c  
              WHERE (c.Type=0 OR c.Type=4) AND c.ArticleID=%s AND c.Type != 6 AND c.Flag = 0 ORDER BY c.ShowIndex asc';
      $result = $this->query($sql,array($articleId));
      $temp = array();
      while($row = $result->fetch_assoc()){
          array_push($temp, $row);
      }
      if($temp){
          $temp = self::mergeDataAndImage($temp, 'FileID');
          foreach ($temp as $k=>$v){
              $temp[$k]['Share'] = $v['Picture'];
              $temp[$k]['FileSize'] = isset($v['Size'])?$v['Size']:'';
              $temp[$k]['FileDescription'] = isset($v['Description'])?$v['Description']:'';
          }
          $articleContent = array_merge($articleContent, $temp);
      }
      $sql = 'SELECT c.ID as ContentID,c.Type,c.ContentInfo as Text,c.IsDetail,c.IsOriginal,
              g.GoodsID,g.GoodsName,g.Price,g.Currency, g.GoodsLink,g.IsBlocked as IsGoodsLinkBlocked,t.TagName as GoodsBrand,g.CmsFileID,g.FileID,c.ShowIndex
               FROM cms_article_content c  
               LEFT JOIN cms_goods g ON c.ContentInfo=g.GoodsID 
               LEFT JOIN cms_tags t on g.GoodsBrand = t.TagID  
               WHERE c.Type=5  AND c.ArticleID=%s AND c.Type != 6 AND c.Flag = 0 ORDER BY c.ShowIndex asc';
      $result = $this->query($sql,array($articleId));
      $temp = array();
      while($row = $result->fetch_assoc()){
          array_push($temp, $row);
      }
      if($temp){
          foreach ($temp as &$tempVal){
              if($tempVal['CmsFileID']){
                  $tempVal['FileID'] = $tempVal['CmsFileID'];
              }
              unset($tempVal['CmsFileID']);
          }
          $temp = self::mergeDataAndImage($temp, 'FileID');
          foreach($temp as $key=>&$item){
              $temp[$key]['GoodsRatio'] = $item['Ratio'];
              $temp[$key]['GoodsPicture'] = $item['Picture'];
              $temp[$key]['GoodsShare'] = $item['Picture'];
              $temp[$key]['GoodsWidth'] = $item['FileWidth'];
              $temp[$key]['GoodsHeight'] = $item['FileHeight'];
              $temp[$key]['GoodsCropX'] = $item['CropX'];
              $temp[$key]['GoodsCropY'] = $item['CropY'];
              $temp[$key]['GoodsCropWidth'] = $item['CropWidth'];
              $temp[$key]['GoodsCropHeight'] = $item['CropHeight'];
              unset($item['Ratio']);
              unset($item['Picture']);
              unset($item['FileWidth']);
              unset($item['FileHeight']);
              unset($item['CropX']);
              unset($item['CropY']);
              unset($item['CropWidth']);
              unset($item['CropHeight']);
          }
          $articleContent = array_merge($articleContent, $temp);
      }
      $sql = 'SELECT c.ID as ContentID,c.Type,c.ContentInfo as Text,m.Title as AudioTitle,m.Cover as FileID,c.ShowIndex
              FROM cms_article_content c  
              LEFT JOIN cms_media_files m on c.ContentInfo=m.MediaID
              WHERE c.Type = 11 AND m.Type=1 AND c.ArticleID=%s AND c.Type != 6 AND c.Flag = 0 ORDER BY c.ShowIndex asc';
      $result = $this->query($sql,array($articleId));
      $temp = array();
      while($row = $result->fetch_assoc()){
          array_push($temp, $row);
      }
      if($temp){
          $temp = self::mergeDataAndImage($temp, 'FileID');
          foreach($temp as $key=>&$item){
              $temp[$key]['AudioPicture'] = $item['Picture'];
              unset($item['Ratio']);
              unset($item['Picture']);
              unset($item['FileWidth']);
              unset($item['FileHeight']);
              unset($item['CropX']);
              unset($item['CropY']);
              unset($item['CropWidth']);
              unset($item['CropHeight']);
          }
          $articleContent = array_merge($articleContent, $temp);
      }
      
      $sql = 'SELECT c.ID as ContentID,c.Type,c.ContentInfo as Text,m1.Title as VideoTitle,m1.Description as VideoDescription,m1.Name as VideoLink ,m1.Cover as FileID,c.ShowIndex
              FROM cms_article_content c
              LEFT JOIN cms_media_files m1 on c.ContentInfo=m1.MediaID  
              WHERE c.Type = 12 AND m1.Type=2 AND c.ArticleID=%s AND c.Type != 6 AND c.Flag = 0 ORDER BY c.ShowIndex asc ';
      $result = $this->query($sql,array($articleId));
      $temp = array();
      while($row = $result->fetch_assoc()){
          array_push($temp, $row);
      }
      if($temp){
          $temp = self::mergeDataAndImage($temp, 'FileID');
          foreach($temp as $key=>&$item){
              $temp[$key]['VideoPicture'] = $item['Picture'];
              $temp[$key]['VideoPictureWidth'] = $item['FileWidth'];
              $temp[$key]['VideoPictureHeight'] = $item['FileHeight'];
              unset($item['Ratio']);
              unset($item['Picture']);
              unset($item['FileWidth']);
              unset($item['FileHeight']);
              unset($item['CropX']);
              unset($item['CropY']);
              unset($item['CropWidth']);
              unset($item['CropHeight']);
          }
          $articleContent = array_merge($articleContent, $temp);
      }
      if($articleContent){
          foreach ($articleContent as $key=>$val){
              $articleContent[$key]['FileSize'] = isset($val['FileSize'])?$val['FileSize']:'';
              $articleContent[$key]['FileID'] = isset($val['FileID'])?$val['FileID']:'';
              $articleContent[$key]['Share'] = isset($val['Share'])?$val['Share']:'';
              $articleContent[$key]['FileDescription'] = isset($val['FileDescription'])?$val['FileDescription']:'';
              $articleContent[$key]['Picture'] = isset($val['Picture'])?$val['Picture']:'';
              $articleContent[$key]['CropX'] = isset($val['CropX'])?$val['CropX']:0;
              $articleContent[$key]['CropY'] = isset($val['CropY'])?$val['CropY']:0;
              $articleContent[$key]['CropWidth'] = isset($val['CropWidth'])?$val['CropWidth']:0;
              $articleContent[$key]['CropHeight'] = isset($val['CropHeight'])?$val['CropHeight']:0;
              $articleContent[$key]['Ratio'] = isset($val['Ratio'])?$val['Ratio']:0;
              $articleContent[$key]['FileWidth'] = isset($val['FileWidth'])?$val['FileWidth']:0;
              $articleContent[$key]['FileHeight'] = isset($val['FileHeight'])?$val['FileHeight']:0;
              $articleContent[$key]['GoodsID'] = isset($val['GoodsID'])?$val['GoodsID']:'';
              $articleContent[$key]['GoodsName'] = isset($val['GoodsName'])?$val['GoodsName']:'';
              $articleContent[$key]['Price'] = isset($val['Price'])?$val['Price']:'';
              $articleContent[$key]['GoodsPicture'] = isset($val['GoodsPicture'])?$val['GoodsPicture']:'';
              $articleContent[$key]['Currency'] = isset($val['Currency'])?$val['Currency']:'';
              $articleContent[$key]['GoodsBrand'] = isset($val['GoodsBrand'])?$val['GoodsBrand']:'';
              $articleContent[$key]['GoodsRatio'] = isset($val['GoodsRatio'])?$val['GoodsRatio']:'';
              $articleContent[$key]['GoodsShare'] = isset($val['GoodsShare'])?$val['GoodsShare']:'';
              $articleContent[$key]['GoodsWidth'] = isset($val['GoodsWidth'])?$val['GoodsWidth']:0;
              $articleContent[$key]['GoodsHeight'] = isset($val['GoodsHeight'])?$val['GoodsHeight']:0;
              $articleContent[$key]['GoodsCropX'] = isset($val['GoodsCropX'])?$val['GoodsCropX']:0;
              $articleContent[$key]['GoodsCropY'] = isset($val['GoodsCropY'])?$val['GoodsCropY']:0;
              $articleContent[$key]['GoodsCropWidth'] = isset($val['GoodsCropWidth'])?$val['GoodsCropWidth']:0;
              $articleContent[$key]['GoodsCropHeight'] = isset($val['GoodsCropHeight'])?$val['GoodsCropHeight']:0;
              $articleContent[$key]['GoodsLink'] = isset($val['GoodsLink'])?$val['GoodsLink']:'';
              $articleContent[$key]['IsGoodsLinkBlocked'] = isset($val['IsGoodsLinkBlocked'])?$val['IsGoodsLinkBlocked']:'';
              $articleContent[$key]['AudioTitle'] = isset($val['AudioTitle'])?$val['AudioTitle']:'';
              $articleContent[$key]['AudioPicture'] = isset($val['AudioPicture'])?$val['AudioPicture']:'';
              $articleContent[$key]['VideoTitle'] = isset($val['VideoTitle'])?$val['VideoTitle']:'';
              $articleContent[$key]['VideoPicture'] = isset($val['VideoPicture'])?$val['VideoPicture']:'';
              $articleContent[$key]['VideoPictureWidth'] = isset($val['VideoPictureWidth'])?$val['VideoPictureWidth']:0;
              $articleContent[$key]['VideoPictureHeight'] = isset($val['VideoPictureHeight'])?$val['VideoPictureHeight']:0;
              $articleContent[$key]['VideoLink'] = isset($val['VideoLink'])?$val['VideoLink']:'';
          }
      }
      $articleContent = $this->arraySort($articleContent, 'ShowIndex');
      foreach ($articleContent as &$content){
          unset($content['ShowIndex']);
      }
      return $articleContent;
    }
    /**
     * 二维数组按照某以键值排序
     * arraySort($array, $keys, $type = SORT_DESC)
     */
    private function arraySort($array, $keys, $type = SORT_ASC) {
        $keysValue = $newArray = array();
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        $type == SORT_ASC ? asort($keysValue) : arsort($keysValue);
        reset($keysValue);
        foreach ($keysValue as $k => $v) {
            array_push($newArray, $array[$k]);
        }
        return $newArray;
    }

    public function getArticleTags($articleId){
        //明星和其他标签分开取
        $sql = "SELECT t.TagID FROM cms_article_tags t WHERE t.ArticleID=%s";
        $allResult = $this->query($sql,array($articleId));
        $allTagId = array();
        while ($allResult->fetch_assoc()){
            array_push($allTagId, $allResult->getData('TagID'));
        }
        $tagList = array();
        if($allTagId){
            $sqlTag = "SELECT DISTINCT t1.TagID,t1.TagName as Name,t1.CategoryID as Category
            FROM cms_article_tags t
            INNER JOIN cms_tags t1 ON t.TagID=t1.TagID AND t1.CategoryID in (3,4,5,6,7,8)
            WHERE t.ArticleID=%s order by t1.CategoryID,t.CreateTime desc";
            
//             var sql = 'SELECT DISTINCT t1.TagID,t1.TagName as Name,t1.CategoryID as Category,f.Status as FashionistaStatus,f1.ServerFileName as Avatar,t2.TagName as SecondName ' +
//             'FROM cms_article_tags t ' +
//             'INNER JOIN cms_tags t1 ON t.TagID=t1.TagID AND t1.CategoryID in (2,3,4,5,6,7,8) ' +
//             'LEFT JOIN cms_fashionistas f ON t.TagID=f.FashionistaID  AND f.FLag = 0 ' +
//             'LEFT JOIN cms_tags t2 ON f.SecondName = t2.TagID AND t2.CategoryID != 11 ' +
//             'LEFT JOIN cms_files f1 ON f.Avatar=f1.FileID ' +
//             'WHERE t.ArticleID=' + articleId + " order by t1.CategoryID,f.Status desc";
            
            $tagResult = $this->query($sqlTag,array($articleId));
            while ($row = $tagResult->fetch_assoc()){
                array_push($tagList, $row);
            }
        }

        //明星
        $celebrityIds = array();
        $sql = "SELECT t.CelebrityID FROM cms_article_celebrity t WHERE t.ArticleID=%s";
        $allResult = $this->query($sql,array($articleId));
        while ($allResult->fetch_assoc()){
            array_push($celebrityIds, $allResult->getData('CelebrityID'));
        }
        $celeArr = array();
        if($celebrityIds){
            $selArr = array(
                \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_ID,
                \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_NAME_CN,
                \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_NAME_EN,
                \haibao\cms\model\filter\Celebrity::CONDITION_FIELD_NAME_STATUS
            );
            $temp = array();
            $celebrityModels = \haibao\jiepai\business\Fashionista::getCelebrityModels($celebrityIds, $selArr);
            if($celebrityModels){
                foreach ($celebrityModels as $k=>$v){
                    array_push($temp, array(
                        'TagID' => $v->Id,
                        'Name' =>$v->NameEn,
                        'Category' => 2,
                        'SecondName' =>$v->NameCn,
                        'Avatar' =>$v->ImageSrc,
                        'FashionistaStatus'=>$v->Status
                    ));
                }
            }
            $celeArr = array_merge($celeArr,$temp);
        }

        return array_merge($celeArr,$tagList);
    }
    /* 文章作者信息 */
    public function getArticleAuthor($articleId){
        $sql = 'SELECT EditorID FROM cms_articles WHERE ArticleID=%s';
        $editorId = $this->query($sql,array($articleId))->fetch_assoc();
        $this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
        $sql = 'SELECT * FROM `Guise` WHERE GuiseId=%s';
        $result = $this->query($sql,array($editorId['EditorID']));
        $dataList = array();
        while ($result->fetch_assoc()){
            $dataList = array('UserID'=>$result->getData('GuiseId'),'NickName'=>$result->getData('Nickname'),'Avatar'=>'','Title'=>1,'Description'=>'街拍编辑');
        }
        if(empty($dataList)){
            $this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_STREET_SNAP_DB );
            $userSql = 'SELECT * FROM cms_users WHERE UserID=%s';
            $haibaoResult = $this->query($userSql,array($editorId['EditorID']));
            while ($haibaoResult->fetch_assoc()){
                $dataList = array('UserID'=>$haibaoResult->getData('UserID'),'NickName'=>$haibaoResult->getData('NickName'),'Avatar'=>'','Title'=>1,'Description'=>$haibaoResult->getData('Description')?$haibaoResult->getData('Description'):'街拍编辑');
            }
        }
//         $sql = 'SELECT u.UserID,u.NickName,f.ServerFileName as Avatar,u.Title,u.Description 
//             FROM cms_articles a 
//             INNER JOIN cms_users u ON a.EditorID=u.UserID
//         LEFT JOIN cms_files f ON u.AvatarID=f.FileID WHERE ArticleID=%s';
        return $dataList;
        
    }
    /* 文章栏目信息 */
    public function getArticleColumns($articleId, $columnId){
        $data = array();
        if($columnId){
            $sql = 'select ColumnName from cms_columns where ColumnID=%s';
            $result = $this->query($sql,array($columnId))->fetch_assoc();
            if($result){
                $data['ColumnName'] = $result['ColumnName'];
                $tagSql = 'SELECT t.TagName FROM cms_article_tags a LEFT JOIN cms_tags t ON a.TagID=t.TagID WHERE a.ArticleID=%s AND t.CategoryID=15 AND t.Flag=0;';
                $resultTag = $this->query($tagSql,array($articleId))->fetch_assoc();
                if($resultTag){
                    $data['SecondC'] = $resultTag['TagName'];
                }
            }
        }
        return $data;
    }

    public function getComments($option,$articleId){
    	$commentId = isset($option['CommentID']) ? $option['CommentID'] : 0;
    	$orderType = isset($option['orderType']) ? $option['orderType'] : 1;
    	$nextCursor = isset($option['nextCursor']) ? $option['nextCursor'] : 0;
    	$prevCursor = isset($option['prevCursor']) ? $option['prevCursor'] : 0;
    	$contentIndex = isset($option['contentIndex']) ? $option['contentIndex'] : 0;
    	if ($commentId == 0) {
    		$commentId = null;
    	}
    	$results = $result2 = array();
    	$result3 = $result4 = array();
    	$userIds = $userInfoArr = array();
    	$temp = array();
    	//     	echo $orderType;exit;
    	if($orderType == 2){
    		$rownoSql = "SELECT rowno FROM (SELECT CommentID,(@rowno:=@rowno+1) as rowno FROM cms_comment ,(SELECT (@rowno:=0)) b WHERE TypeID = " . $articleId .
    		" AND Type = 0  AND Flag=0 AND AuditStatus!=2 ORDER BY Scores DESC,CreateTime DESC) c " .
    		"WHERE c.CommentID = ";
    		$commonSql = "SELECT CommentID,Scores,Content,UserID,CreateTime,SensitiveWords,Pictures,AuditStatus,rowno FROM" .
    				" (SELECT t1.CommentID,t1.Scores,t1.Content,t1.UserID,t1.CreateTime,t1.SensitiveWords,t1.AuditStatus,t1.FileID as Pictures,(@rowno:=@rowno+1) as rowno" .
    				" FROM cms_comment t1,(SELECT (@rowno:=0)) c " .
    				" WHERE t1.TypeID = " . $articleId .
    				" AND t1.Type = 0 AND t1.Flag = 0 AND t1.AuditStatus != 2 ORDER BY Scores DESC,CreateTime DESC ) d ";
    		$sql2 = "";
    		$sql11 = "";
    		$sql12 = "";
    
    		if ($commentId) {
    			$sql2 = $rownoSql . $commentId;
    		} else if ($nextCursor) {
    			$sql2 = $rownoSql . $nextCursor;
    		} else if ($prevCursor) {
    			$sql2 = $rownoSql . $prevCursor;
    		}
    
    		if($sql2){
    			$result2 = $this->query($sql2)->fetch_assoc();
    			if(!$result2['rowno']){
    				$results = array();
    			}else {
    				$index = $result2['rowno'];
    				if($commentId){
    					$sql11 = $commonSql . " WHERE rowno > " . $index . ' AND rowno < ' . ($index + 16) .';';
    					$sql12 = $commonSql . " WHERE rowno <= " . $index . " ORDER BY rowno DESC LIMIT 16;";
    
    					$result1 = $this->query($sql11);
    					$result2 = $this->query($sql12);
    					while ($row = $result1->fetch_assoc()){
    						array_push($userIds, $row['UserID']);
    						array_push($result3, $row);
    					}
    					while ($row = $result2->fetch_assoc()){
    						array_push($userIds, $row['UserID']);
    						array_push($result4, $row);
    					}
    					//处理user
    					$userInfoArr = \haibao\jiepai\business\User::getNickNameByUserIds($userIds);
    					foreach ($result3 as $key=>$val){
    						if(isset($userInfoArr[$val['UserID']])){
    							$result3[$key]['NickName'] = $userInfoArr[$val['UserID']];
    						}else {
    							$result3[$key]['NickName'] = '';
    						}
    					}
    					foreach ($result4 as $key=>$val){
    						if(isset($userInfoArr[$val['UserID']])){
    							$result4[$key]['NickName'] = $userInfoArr[$val['UserID']];
    						}else {
    							$result4[$key]['NickName'] = '';
    						}
    					}
    						
    					$results[0] = $result3;
    					$results[1] = $result4;
    
    					foreach ($results[1] as $key=>$val){
    						$temp[$key] = $val['rowno'];
    					}
    					array_multisort($temp,SORT_ASC,$results[1]);
    					if(count($results[1])>15){
    						$results[1] = array_slice($results[1], 1,16);
    					}
    					$results = self::getArticleCommentType1($results, $orderType);
    					return $results;
    				}else {
    					if($nextCursor){
    						$sql11 = $commonSql . " WHERE rowno > " . $index . " LIMIT " . ((int)(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE)) + 1) .";";
    					}elseif ($prevCursor){
    						$sql11 = commonSql . " WHERE rowno BETWEEN " . ($index - (int)(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE)) + 1) . " AND " . index .";";
    					}
    					$result1 = $this->query($sql11);
    
    					while ($row = $result1->fetch_assoc()){
    						array_push($userIds, $row['UserID']);
    						array_push($result3, $row);
    					}
    					//处理user
    					$userInfoArr = \haibao\jiepai\business\User::getNickNameByUserIds($userIds);
//     					$userInfoArr = \haibao\user\business\User::getNickNameByUserIds($userIds);
    					foreach ($result3 as $key=>$val){
    						if(isset($userInfoArr[$val['UserID']])){
    							$result3[$key]['NickName'] = $userInfoArr[$val['UserID']];
    						}else {
    							$result3[$key]['NickName'] = '';
    						}
    					}
    						
    					$results = $result3;
    					return self::getArticleCommentType2($prevCursor, $nextCursor, $results);
    				}
    			}
    		}else {
    			$result1 = $this->query($commonSql." WHERE rowno > 0 LIMIT ".((int)(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE)) + 1).";");
    			while ($row = $result1->fetch_assoc()){
    				array_push($result3, $row);
    				array_push($userIds, $row['UserID']);
    			}
    			 
    			//处理user
    			$userInfoArr = \haibao\jiepai\business\User::getNickNameByUserIds($userIds);
//     			$userInfoArr = \haibao\user\business\User::getNickNameByUserIds($userIds);
    			foreach ($result3 as $key=>$val){
    				if(isset($userInfoArr[$val['UserID']])){
    					$result3[$key]['NickName'] = $userInfoArr[$val['UserID']];
    				}else {
    					$result3[$key]['NickName'] = '';
    				}
    			}
    			 
    			$results = $result3;
    			return self::getArticleCommentType2($prevCursor, $nextCursor, $results);
    		}
    	}else {
    		$commonSql = "SELECT t1.CommentID,t1.Scores,t1.Content,t1.SensitiveWords,t1.UserID,t1.CreateTime,t2.NickName,t2.AvatarID as Avatar,t1.AuditStatus,t1.FileID as Pictures FROM cms_comment t1 " .
    				"LEFT JOIN cms_users t2 on t1.UserID = t2.UserID " .
    				"WHERE t1.TypeID = " . $articleId ." AND t1.Type = 0 AND t1.Flag = 0 AND t1.AuditStatus != 2 ";
    		if ($commentId) {
    			$sql = $commonSql . " AND t1.CommentID >= " . $commentId . " ORDER BY t1.CommentID ASC LIMIT 16;";
    			$sql1 = "";
    			$sql1 = $commonSql . " AND t1.CommentID < " . $commentId . " ORDER BY t1.CommentID DESC LIMIT 16;";
    
    
    			$result1 = $this->query($sql);
    			$result2 = $this->query($sql1);
    			while ($row = $result1->fetch_assoc()){
    				array_push($result3, $row);
    				array_push($userIds, $row['UserID']);
    			}
    			while ($row = $result2->fetch_assoc()){
    				array_push($result4, $row);
    				array_push($userIds, $row['UserID']);
    			}
    			 
    			//处理user
    			$userInfoArr = \haibao\jiepai\business\User::getNickNameByUserIds($userIds);
//     			$userInfoArr = \haibao\user\business\User::getNickNameByUserIds($userIds);
    			foreach ($result3 as $key=>$val){
    				if(isset($userInfoArr[$val['UserID']])){
    					$result3[$key]['NickName'] = $userInfoArr[$val['UserID']];
    				}else {
    					$result3[$key]['NickName'] = '';
    				}
    			}
    			foreach ($result4 as $key=>$val){
    				if(isset($userInfoArr[$val['UserID']])){
    					$result4[$key]['NickName'] = $userInfoArr[$val['UserID']];
    				}else {
    					$result4[$key]['NickName'] = '';
    				}
    			}
    			 
    			$results[0] = $result3;
    			$results[1] = $result4;
    			return self::getArticleCommentType1($results, $orderType);
    		} else {
    			$sql = "";
    			if ($nextCursor) {
    				$sql = $commonSql . " AND t1.CommentID < " . $nextCursor;
    			} else if ($prevCursor) {
    				$sql = $commonSql . " AND t1.CommentID > " . $prevCursor;
    			} else {
    				$sql = $commonSql;
    			}
    			$sql .= " ORDER BY t1.CommentID DESC LIMIT " . ((int)(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE)) + 1);
                $result1 = $this->query($sql);
    			while ($row = $result1->fetch_assoc()){
    				array_push($result3, $row);
    				array_push($userIds, $row['UserID']);
    			}
    			//处理user
    			$userInfoArr = \haibao\jiepai\business\User::getNickNameByUserIds($userIds);
//     			$userInfoArr = \haibao\user\business\User::getNickNameByUserIds($userIds);
    			foreach ($result3 as $key=>$val){
    				if(isset($userInfoArr[$val['UserID']])){
    					$result3[$key]['NickName'] = $userInfoArr[$val['UserID']];
    				}else {
    					$result3[$key]['NickName'] = '';
    				}
    			}
    			$results = $result3;
    			return self::getArticleCommentType2($prevCursor, $nextCursor, $results);
    		}
    	}
    }

    public function getArticleCommentType1($results, $orderType) {
    	$prev = $next = 0;
    	$temp = array();
    	$returnRes = array();
    	if ($orderType == 1) {
    		foreach ($results[0] as $key=>$val){
    			$temp[$key] = $val['CommentID'];
    		}
    		array_multisort($temp,SORT_DESC,$results[0]);
    	}
    	if (count($results[0])> 15) {
    		$results[0] = array_slice($results[0], 1,16);
    		$prev = $results[0][0]['CommentID'];
    	}
    	if (count($results[1]) > 15) {
    		$results[1] = array_slice($results[1], 0,15);
    		$next = $results[1][14]['CommentID'];
    	}
    	if ($orderType == 1) {
    		$results = array_merge($results[0],$results[1]);
    	} else {
    		$results = array_merge($results[1],$results[0]);
    	}
    	$returnRes['results'] = $results;
    	$returnRes['next'] = $next;
    	$returnRes['prev'] = $prev;
    	return $returnRes;
    }

    public function getArticleCommentType2($prevCursor, $nextCursor, $results) {
    	$prev = $next = 0;
    	$returnRes = array();
    	if (count($results) >\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE) ) {
    		if ($nextCursor) {
    			$results = array_slice($results,0, 30);
    			$next = $results[count($results)- 1]['CommentID'];
    			$prev = $nextCursor;
    		} else if ($prevCursor) {
    			$results = $results = array_slice($results,1, 31);
    			$next = $prevCursor;
    			$prev = $results[0]['CommentID'];
    		} else {
    			$results = array_slice($results,0, 30);
    			$next = $results[count($results)- 1]['CommentID'];
    		}
    	}
    	$returnRes['results'] = $results;
    	$returnRes['next'] = $next;
    	$returnRes['prev'] = $prev;
    	return $returnRes;
    }
    
    public function getCommentReply($commentIds){
    	$commentIds = implode(',', $commentIds);
    	$commentReply = $userIds = array();
    	$sql = "SELECT t1.ReplyID, t1.RepliedID,t1.UserID,t1.CommentID,t1.Content,t1.SensitiveWords,t1.RepliedUserID,t1.AuditStatus FROM cms_comment_reply t1" .
    			" WHERE t1.Flag = 0 AND t1.AuditStatus != 2 AND t1.CommentID IN (".$commentIds.")";
    	$result = $this->query($sql);
    	while ($row = $result->fetch_assoc()){
    		$temp = array();
    		$temp['ReplyID'] = $row['ReplyID'];
    		$temp['Type'] = $row['RepliedID'] ? 2:1;
    		$temp['RepliedID'] = $row['RepliedID'];
    		$temp['ReplyContent'] = $row['Content'];
    		$temp['SensitiveWords'] = $row['SensitiveWords'];
    		$temp['AuditStatus'] = $row['AuditStatus'];
    		$temp['User']['UserID'] = $row['UserID'];
    		$temp['User']['NickName'] = '';
    		$temp['User']['Avatar'] = '';
    		$temp['RepliedUser']['UserID'] = $row['RepliedUserID'];
    		$temp['RepliedUser']['NickName'] = '';
    		$temp['Pictures'] = $this->getCommentPictures($row['ReplyID'],2);
    		$commentReply[$row['CommentID']][] =  $temp;
    		array_push($userIds, $row['RepliedUserID']);
    		array_push($userIds, $row['UserID']);
    	}
    	if($userIds){	
//     		$userInfoArr = \haibao\user\business\User::getNickNameByUserIds($userIds);
    		$userInfoArr = \haibao\jiepai\business\User::getNickNameByUserIds($userIds);
    	}
//     	print_r($userIds);exit;
    	//处理user
    	if($commentReply){
    		foreach ($commentReply as $key=>$modelArr){
	    		foreach ($modelArr as $k=>$v){
	    			$userId = $v['User']['UserID'];
	    			$repliedUser = $v['RepliedUser']['UserID'];
	    			if(isset($userInfoArr[$userId]) && $userInfoArr[$userId]){
	    				$commentReply[$key][$k]['User']['NickName'] = $userInfoArr[$userId];
	    				$commentReply[$key][$k]['User']['Avatar'] = \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\Config::CLASSLIBRARY_CONFIG_HOST_BBS) . '/uc_server/avatar.php?uid='.$userId.'&size=middle';
	    			}else {
	    				$commentReply[$key][$k]['User']['NickName'] = '';
	    				$commentReply[$key][$k]['User']['Avatar'] = '';
	    			}
	    			if(isset($userInfoArr[$repliedUser]) && $userInfoArr[$repliedUser]){
	    				$commentReply[$key][$k]['RepliedUser']['UserID'] = $repliedUser;
	    				$commentReply[$key][$k]['RepliedUser']['NickName'] = $userInfoArr[$repliedUser];
	    			}else {
	    				$commentReply[$key][$k]['RepliedUser'] = (object)array();
	    			}
	    		}
	    	}
    	}
    	
    	return $commentReply;
    }

    public function getOldStatistic($articleIds){
        $str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
        $sql = 'SELECT ArticleID,OldJiepaiStatistic FROM cms_articles WHERE ArticleID IN ('.$str.')';
        $result = $this->query($sql,$articleIds);
        $dataList = array();
        while ($result->fetch_assoc()){
            $dataList[$result->getData('ArticleID')] = $result->getData('OldJiepaiStatistic');
        }
        return $dataList;
    }

    public function getArticleByComment($commentId){

        $sql = "SELECT t2.ArticleID,t2.ContentInfo,t4.Type from cms_comment t1 " .
            "LEFT JOIN cms_article_content t2 on t1.TypeID = t2.ArticleID AND t1.Type = 0 AND t2.Type = 0 " .
            "LEFT JOIN cms_articles t4 ON t2.ArticleID = t4.ArticleID " .
            "WHERE t1.CommentID = %s";

        $result = $this->query($sql,array($commentId))->fetch_assoc();

        return $result?self::mergeOneDataAndImage($result, $result['ContentInfo']):array();
    }
    //获取专栏回顾文章列表
    public function getSpecialReviews($articleId, $type, $publishtime){
        $temp = array();
        $sql = "SELECT ca.ArticleID,ca.Type,ca.Title,ca.Subtitle as KeyWord,cac.ContentInfo
            FROM cms_articles ca 
            LEFT JOIN cms_article_content cac ON ca.ArticleID=cac.ArticleID 
            WHERE ca.Flag=0 AND cac.Type=0 AND cac.Flag=0 AND ca.PublishStatus=1 AND ca.Type= ".$type;
        $result = $this->getSpecialFirstArticle($type);
        if($result && $result['ArticleID'] == $articleId){//第一期显示最新两期
            $sql .= ' AND ca.ArticleID != '.$articleId.' ORDER BY ca.PublishTime desc LIMIT 2';
            $isFirst = true;
        }else{
            $isFirst = false;
        }
        if($isFirst){
            $dataRes = $this->query($sql);
            while ($row = $dataRes->fetch_assoc()){
                array_push($temp, $row);
            }
        }else{
            $lastArticle = $this->getSpecialLastArticle($type);//最新一期显示之前两期
            if (($lastArticle && $lastArticle['ArticleID']) == $articleId) {
                $sql .= " AND ca.PublishTime < '".$lastArticle['PublishTime']. "' ORDER BY PublishTime desc LIMIT 2";
                $dataRes = $this->query($sql);
                while ($row = $dataRes->fetch_assoc()){
                    array_push($temp, $row);
                }
            } else {//显示最新一期和上一期
                $newSql1 = $sql . " ORDER BY ca.PublishTime desc LIMIT 1;";
                $newSql2 = $sql ." AND ca.PublishTime < '" .$publishtime. "' ORDER BY PublishTime desc LIMIT 1";
                $temp = $this->query($newSql1)->fetch_assoc()+$this->query($newSql2)->fetch_assoc();
            }
        }
        if($temp){
            return $this->mergeDataAndImage($temp,'ContentInfo');
        }
        return array();
        
    }
    
    //获取专栏第一期ID
    public function getSpecialFirstArticle($type) {
        $sql = "SELECT ArticleID,PublishTime from cms_articles WHERE Flag=0 and PublishStatus=1 AND Type=%s AND PublishTime < '".date('Y-m-d H:i:s')."' ORDER BY PublishTime asc LIMIT 1;";
        return $this->query($sql,array($type))->fetch_assoc();
    }
    //获取专栏最新一期ID
    public function getSpecialLastArticle($type) {
        $sql = "SELECT ArticleID,PublishTime from cms_articles WHERE Flag=0 and PublishStatus=1 AND Type=%s AND PublishTime < '".date('Y-m-d H:i:s')."' ORDER BY PublishTime desc LIMIT 1;";
        return $this->query($sql,array($type))->fetch_assoc();
    }
    public function checkCommentValidStatus($type,$obj){
    	$sql = "";
    	if ($type == 'comment') {
    		$sql = "SELECT CreateTime FROM cms_comment WHERE Type = 0 AND TypeID = " . $obj['TypeID'] . " AND UserID = " .$obj['UserID']  . " AND Flag = 0 ORDER BY CreateTime DESC LIMIT 1;";
    	} else if ($type == 'reply') {
    		$sql = "SELECT ReplyTime as CreateTime FROM cms_comment_reply WHERE CommentID = " . $obj['TypeID'] . " AND UserID = "  .$obj['UserID']  . " AND Flag = 0 ORDER BY ReplyTime DESC LIMIT 1;";
    	}
    	$result = $this->query($sql)->fetch_assoc();
    	if(!$result){
    		return true;
    	}else {
    		return (strtotime(date('Y-m-d H:i:s')) - strtotime($result['CreateTime'])) > \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENT_TIME_LIMIT) ? true : false;
    	}
    }
    public function getCommentTotalCount($articleId){
        $sql = "select sum(a.count) as sumcount from (
                	SELECT COUNT(ReplyID) as count FROM cms_comment_reply WHERE Flag = 0 AND AuditStatus != 2 AND CommentID IN (
                		SELECT CommentID FROM cms_comment where Flag = 0 AND AuditStatus != 2 AND Type=0 and TypeID = ".$articleId."
                	)
                	union all
                	SELECT COUNT(CommentID) as Comment FROM cms_comment where Flag = 0 AND AuditStatus != 2 AND Type=0 and TypeID = ".$articleId."
                ) a";
        $result = $this->query($sql);
        $count = $result->fetch_assoc();
        return isset($count['sumcount'])?$count['sumcount']:0;
    }
    public function getArticleGoods($articleIds) {
        $sql = "SELECT c.ArticleID,cgp.FileID,cgp.GoodsID,c.IsOriginal FROM cms_article_content c  " .
        "LEFT JOIN cms_goods_pictures cgp on cgp.GoodsID = c.ContentInfo " .
        " WHERE c.Type=5 AND c.ArticleID IN (" .implode(',', $articleIds).") AND c.Flag = 0  ORDER BY c.ShowIndex limit 4";
        $result = $this->query($sql);
        $dataList = array();
        while ($row = $result->fetch_assoc()){
            $dataList[$result->getData('ArticleID')] = $row;
        }
        if($dataList){
            $dataList = $this->mergeDataAndImage($dataList,'FileID');
        }
        return $dataList;
    }

    public function getArticleInfo($articleId, $contentType){
        $sql = 'SELECT a.SubtitleType as KeyTitle,c.Type as ContentType,a.Subtitle as KeyWord,a.ArticleID,a.Title,a.Type,a.CreateTime,a.PublishTime,c.ContentInfo,a.ColumnID ' .
            'FROM cms_articles a ' .
            'LEFT JOIN cms_article_content c on a.ArticleID=c.ArticleID and (c.Type=6 OR c.Type=0) ' .
            'WHERE a.ArticleID=%s';

        $result = $this->normalQuery($sql, array($articleId));

        $result = array_filter($result,function($article)use($contentType){
            return $article['ContentType'] == $contentType;
        });

        if($result){
            return self::mergeDataAndImage($result);
        }
        return $result;
    }
}
